Delphi的16进制数转化为2进制数众所周知,Delphi中有个HexToBin的函数,但是这个函数转化的二进制数总有问题,得不到我们想要的结果。我今天把他干脆重写了一遍,希望对大家有所帮助。 function HexToBin(sHex: string):string; var sHexBuf: array [0..65535] of Char; i, nLen: Integer; sResult: string; begin sHex := UpperCase(sHex); for i := 0 to 65535 do begin sHexBuf[i] := #0; end; StrPCopy(sHexBuf, sHex); nLen := Length(sHex); sResult := ''; for i := 0 to nLen - 1 do begin case sHexBuf[i] of '0': sResult := sResult + '0000'; '1': sResult := sResult + '0001'; '2': sResult := sResult + '0010'; '3': sResult := sResult + '0011'; '4': sResult := sResult + '0100'; '5': sResult := sResult + '0101'; '6': sResult := sResult + '0110'; '7': sResult := sResult + '0111'; '8': sResult := sResult + '1000'; '9': sResult := sResult + '1001'; 'A': sResult := sResult + '1010'; 'B': sResult := sResult + '1011'; 'C': sResult := sResult + '1100'; 'D': sResult := sResult + '1101'; 'E': sResult := sResult + '1110'; 'F': sResult := sResult + '1111'; else break; end;//end case end; while Pos('0', sResult) = 1 do Delete(sResult, 1, 1); Result := sResult; end;
上面的这个效率是不是有问题呀。每次都要分配64K内存,循环65535 次。function HexToBin(Const AHex:String):String; Const AStrArr:Array [$0..$F] of String=('0000','0001','0010','0011', '0100','0101','0110','0111','1000','1001','1010','1011', '1100','1101','1110','1111'); var i,L:integer; AIndex:Integer; begin AIndex:=1; L:=Length(AHex); SetLength(Result,L*4); for i:=1 to L do begin StrPCopy(@Result[AIndex],AStrArr[StrToInt('$' + AHex[i])]); inc(AIndex,4); end; end;
一般可以用 TMemoryStream
看下帮助就可
function HexToBin(sHex: string):string;
var
sHexBuf: array [0..65535] of Char;
i, nLen: Integer;
sResult: string;
begin
sHex := UpperCase(sHex);
for i := 0 to 65535 do
begin
sHexBuf[i] := #0;
end;
StrPCopy(sHexBuf, sHex);
nLen := Length(sHex);
sResult := '';
for i := 0 to nLen - 1 do
begin
case sHexBuf[i] of
'0': sResult := sResult + '0000';
'1': sResult := sResult + '0001';
'2': sResult := sResult + '0010';
'3': sResult := sResult + '0011';
'4': sResult := sResult + '0100';
'5': sResult := sResult + '0101';
'6': sResult := sResult + '0110';
'7': sResult := sResult + '0111';
'8': sResult := sResult + '1000';
'9': sResult := sResult + '1001';
'A': sResult := sResult + '1010';
'B': sResult := sResult + '1011';
'C': sResult := sResult + '1100';
'D': sResult := sResult + '1101';
'E': sResult := sResult + '1110';
'F': sResult := sResult + '1111';
else
break;
end;//end case
end;
while Pos('0', sResult) = 1 do
Delete(sResult, 1, 1);
Result := sResult;
end;
Const
AStrArr:Array [$0..$F] of String=('0000','0001','0010','0011',
'0100','0101','0110','0111','1000','1001','1010','1011',
'1100','1101','1110','1111');
var
i,L:integer;
AIndex:Integer;
begin
AIndex:=1;
L:=Length(AHex);
SetLength(Result,L*4);
for i:=1 to L do
begin
StrPCopy(@Result[AIndex],AStrArr[StrToInt('$' + AHex[i])]);
inc(AIndex,4);
end;
end;