中文与二进制字节(十六进制)的转换(100分)

  • 主题发起人 主题发起人 zhixding
  • 开始时间 开始时间
Z

zhixding

Unregistered / Unconfirmed
GUEST, unregistred user!
IC卡中存取为二进制,电脑显示须为中文(200分)

1.中文转换二进制字节(十六进制)
2.二进制字节(十六进制)转换中文
 
function Str2Hex(Str: string): string;
var
StrResult, Temp: string;
I: Integer;
begin
StrResult := '';
for I := 0 to Length(Str) - 1 do
begin
Temp := Format('%x', [Ord(Str[I + 1])]);
if Length(Temp) = 1 then Temp := '0' + Temp;
StrResult := StrResult + Temp;
end;
Result := StrResult;
end;

function Hex2Str(StrHex: string): string;
function HexToInt(Hex: string): Integer;
var
I, Res: Integer;
ch: Char;
begin
Res := 0;
for I := 0 to Length(Hex) - 1 do
begin
ch := Hex[I + 1];
if (ch >= '0') and (ch <= '9') then
Res := Res * 16 + Ord(ch) - Ord('0')
else if (ch >= 'A') and (ch <= 'F') then
Res := Res * 16 + Ord(ch) - Ord('A') + 10
else if (ch >= 'a') and (ch <= 'f') then
Res := Res * 16 + Ord(ch) - Ord('a') + 10
else raise Exception.Create('Error: not a Hex String');
end;
Result := Res;
end;

var
Str, Temp: string;
I: Integer;
begin
Str := '';
for I := 0 to Length(StrHex) div 2 - 1 do
begin
Temp := Copy(StrHex, I * 2 + 1, 2);
Str := Str + Chr(HexToInt(Temp));
end;
Result := Str;
end;

procedure TForm1.Button1Click(Sender: TObject);
var s,ss:string;
begin
s:='中华人民共和国';
ss:=Str2Hex(s);
showmessage(ss);
s:=Hex2Str(ss);
showmessage(s);
end;
 
to iseek,以前写的大家互相学习

function HexToStr( //十六进制字符串处理成字符串
mHex: string //十六进制字符串
): string; //返回处理后的字符串
var
I: Integer;
begin
Result := '';
mHex := StringReplace(mHex, #32, '', [rfReplaceAll]);
for I := 1 to Length(mHex) div 2 do
Result := Result + Chr(StrToIntDef('$' + Copy(mHex, I * 2 - 1, 2), 0));
end; { HexToStr }

function StrToHex( //字符串处理成十六进制字符串
mStr: string; //字符串
mSpace: Boolean = False //是否用空格分开
): string; //返回处理后的十六进制字符串
const
cSpaceStr: array[Boolean] of string = ('', #32);
var
I: Integer;
begin
Result := '';
for I := 1 to Length(mStr) do
Result := Format('%s%s%.2x', [Result, cSpaceStr[mSpace], Ord(mStr)]);
if mSpace then Delete(Result, 1, 1);
end; { StrToHex }
 
后退
顶部