//Value:二进制字符串如:11000111 Function ConvertBinToStr(Value : ansistring):ansistring; //把二进制数据转化为字符串 Var tempHex : ansistring; i, tempInt : integer; begin Result := ''; if trim(Value) = '' then Exit; tempHex := BinToHexEachOther(Value,true);//二进制转成十六进制 i := 0; Repeat begin i := i + 1; tempInt := HexCharToInt(tempHex[i]); i := i + 1; tempInt := tempInt * 16 + HexCharToInt(tempHex[i]); //以上将两位十六进制数转变为一个十进制数 Result := Result + AnsiChar(TempInt); //转成ASCII码 end; Until i >= length(tempHex) end; //把二进制串转换成十六进制串或相反 function BinToHexEachOther(ValueA : string; Action : Boolean) : string; var ValueArray1 : Array [0..15] of string[4]; ValueArray2 : Array [0..15] of char; i : shortint; begin //数组初始化 ValueArray1[0] := '0000'; ValueArray1[1] := '0001'; ValueArray1[2] := '0010'; ValueArray1[3] := '0011'; ValueArray1[4] := '0100'; ValueArray1[5] := '0101'; ValueArray1[6] := '0110'; ValueArray1[7] := '0111'; ValueArray1[8] := '1000'; ValueArray1[9] := '1001'; ValueArray1[10] := '1010'; ValueArray1[11] := '1011'; ValueArray1[12] := '1100'; ValueArray1[13] := '1101'; ValueArray1[14] := '1110'; ValueArray1[15] := '1111'; for i := 0 to 15 do if i >= 10 then ValueArray2[i] := chr(65 + (i - 10)) else ValueArray2[i] := inttostr(i)[1]; Result := ''; if Action then begin //二进制串转换成十六进制串 if (Length(ValueA) MOD 4 <> 0) then ValueA := stringofchar('0',Length(ValueA) MOD 4) + ValueA; while (Length(ValueA) >= 4) do begin for i := 0 to 15 do if Copy(ValueA,1,4) = ValueArray1[i] then Result := Result + ValueArray2[i]; ValueA := Copy(ValueA,5,Length(ValueA) - 4); end; end else begin //十六进制串转换成二进制串 while (Length(ValueA) >= 1) do begin for i := 0 to 15 do if Copy(ValueA,1,1) = ValueArray2[i] then Result := Result + ValueArray1[i]; ValueA := Copy(ValueA,2,Length(ValueA) - 1); end; end; end; //十六进制字符转换成整数 function HexCharToInt(HexToken : ansichar):Integer; begin Result:=0; if (HexToken>#47) and (HexToken<#58) then { chars 0....9 } Result:=Ord(HexToken)-48 else if (HexToken>#64) and (HexToken<#71) then { chars A....F } Result:=Ord(HexToken)-65 + 10; end;
http://blog.csdn.net/shuaihj/article/details/6770779