function IntToBinaryStr(TheVal: LongInt): string; var counter: LongInt; begin {This part is here because we remove leading zeros. That means that a zero value would return an empty string.} if TheVal = 0 thenbegin result := '0'; exit; end; result := ''; counter := $80000000; {Suppress leading zeros} while ((counter and TheVal) = 0) dobegin counter := counter shr 1; if (counter = 0) then break; {We found our first "1".} end; while counter > 0 dobegin if (counter and TheVal) = 0 then result := result + '0' else result := result + '1'; counter := counter shr 1; end; end;
// 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;
6.十六进制转换二进制
function HexToBin(Hexadecimal: string): string; const BCD: array [0..15] ofstring = ('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;
7.八进制和十进制的转换
function OctToInt(Value: string): Longint; var i: Integer; int: Integer; begin int := 0; for i := 1 to Length(Value) do begin int := int * 8 + StrToInt(Copy(Value, i, 1)); end; Result := int; end;
function IntToOct(Value: Longint; digits: Integer): string; var rest: Longint; oct: string; i: Integer; begin oct := ''; while Value <> 0 do begin rest := Value mod 8; Value := Value div 8; oct := IntToStr(rest) + oct; end; for i := Length(oct) + 1 to digits do oct := '0' + oct; Result := oct; end;