二進制與十進制互相轉換.. |
|
TOMMY
一般會員 發表:16 回覆:32 積分:9 註冊:2002-03-15 發送簡訊給我 |
|
hagar
版主 發表:143 回覆:4056 積分:4445 註冊:2002-04-14 發送簡訊給我 |
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;
|
TOMMY
一般會員 發表:16 回覆:32 積分:9 註冊:2002-03-15 發送簡訊給我 |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |