use*_*ser 4 delphi unicode hex
我曾经使用这个函数将十六进制字符串转换为Delphi 6中的字符串:
const
testSign = '207F8060287F585054505357FFD55861';
function Hex2Dec(const data: string): byte;
var
nH1, nH2: byte;
begin
if data[1] in ['0' .. '9'] then
nH1 := strtoint(data[1])
else
nH1 := 9 + ord(data[1]) - 64;
if data[2] in ['0' .. '9'] then
nH2 := strtoint(data[2])
else
nH2 := 9 + ord(data[2]) - 64;
Result := nH1 * 16 + nH2;
end;
function HexStrToStr(const HexStr: string): string;
var
BufStr: string;
LenHex: Integer;
x, y: Integer;
begin
LenHex := Length(HexStr) div 2;
x := 1;
y := 0;
while y <> LenHex do
begin
Inc(y);
BufStr := BufStr + Chr(Hex2Dec(HexStr[x] + HexStr[x + 1]));
Inc(x, 2);
end;
Result := BufStr;
end;
Run Code Online (Sandbox Code Playgroud)
现在我想在Delphi 2010中使用该功能.
const
testSign: AnsiString = '207F8060287F585054505357FFD55861';
function Hex2Dec(const data: ansistring): byte;
var
nH1, nH2: byte;
begin
if data[1] in ['0' .. '9'] then
nH1 := strtoint(data[1])
else
nH1 := 9 + ord(data[1]) - 64;
if data[2] in ['0' .. '9'] then
nH2 := strtoint(data[2])
else
nH2 := 9 + ord(data[2]) - 64;
Result := nH1 * 16 + nH2;
end;
function HexStrToStr(const HexStr: ansistring): ansistring;
var
BufStr: ansistring;
LenHex: Integer;
x, y: Integer;
begin
LenHex := Length(HexStr) div 2;
x := 1;
y := 0;
while y <> LenHex do
begin
Inc(y);
BufStr := BufStr + Chr(Hex2Dec(HexStr[x] + HexStr[x + 1]));
Inc(x, 2);
end;
Result := BufStr;
end;
Run Code Online (Sandbox Code Playgroud)
D6中第一个代码的输出:
' '#$7F'€`('#$7F'XPTPSWÿÕXa'
Run Code Online (Sandbox Code Playgroud)
D2010中第二个代码的输出:
' '#$7F#$0080'`('#$7F'XPTPSWÿÕXa'
Run Code Online (Sandbox Code Playgroud)
如何在D2010中修复代码,以便它可以产生与D6相同的结果?
除了其他人提供的解决方案,您还可以使用内置功能:
function HexStrToStr(const HexStr: string): string;
var
tmp: AnsiString;
begin
Assert(not Odd(Length(HexStr)), 'HexToStr input length must be an even number');
SetLength(tmp, Length(HexStr) div 2);
HexToBin(PWideChar(HexStr), @tmp[1], Length(tmp));
result := tmp;
end;
Run Code Online (Sandbox Code Playgroud)
此实现假定十六进制编码的字符串首先是Ansistring.为了灵活性,我建议改用TBytes.
| 归档时间: |
|
| 查看次数: |
8357 次 |
| 最近记录: |