代碼: 選擇全部
1.二進制 <==> 十進制
// Binary to Integer
function BinToInt(value: string): Integer;
var i, ivalueSize: Integer;
begin
Result := 0;
ivalueSize := Length(value);
for i := ivalueSize downto 1 do
if value[i] = '1' then Result := Result + (1 shl (ivalueSize - i));
end;
// Integer to Binary
function IntToBin(value: Longint; Digits: Integer): string;
var i: Integer;
begin
Result := '';
for i := Digits downto 0 do
if value and (1 shl i) <> 0 then
Result := Result + '1'
else
Result := Result + '0';
end;
2.二進制 <==> 十六進制
// Hexadecimal to Binary
function HexToBin(Hexadecimal: string): string;
const
BCD: array [0..15] of string =
('0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111');
var
i: integer;
begin
for i := Length(Hexadecimal) downto 1 do
Result := BCD[StrToInt('$' + Hexadecimal[i])] + Result;
end;
// Binary to Hexadecimal
function BinToHex(Binario:string):string;
const
BCD: array [0..15] of string=
('0000','0001','0010','0011','0100','0101','0110','0111',
'1000','1001','1010','1011','1100','1101','1110','1111');
HEX: array [0..15] of char=
('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
var
i,n:integer;
sTemp:string;
sNibble:string;
begin
Result:='';
sTemp:=Binario+Copy('000',1,Length(Binario) mod 4);
for i:=0 to (Length(Binario) shr 2)-1 do
begin
sNibble:=Copy(sTemp,(i shl 2)+1,4);
n:=8;
while (sNibble <> BCD[n]) do
if sNibble < BCD[n] then Dec(n) else Inc(n);
Result:=Result+HEX[n];
end;
end;