Converting between decimal, binary, and hexadecimal representation



USES
StrUtils, SysUtils;

FUNCTION DecToBin(N: int64): STRING;
VAR
i: integer;
neg: boolean;
BEGIN
IF N = 0 THEN BEGIN
result := ’0’;
exit
END;
SetLength(result, SizeOf(N) * 8);
neg := N < 0;
9
N := Abs(N);
i := 1;
WHILE N <> 0 DO BEGIN
IF N AND 1 = 1 THEN
result[i] := ’1’
ELSE
result[i] := ’0’;
N := N SHR 1;
Inc(i);
END;
IF neg THEN BEGIN
result[i] := ’’;
Inc(i);
END;
Delete(result, i, length(result));
result := ReverseString(result);
END;

FUNCTION DecToHex(N: int64): STRING;
BEGIN
IF N < 0 THEN
result := ’’
+ Format(’%0x’, [Abs(N)])
ELSE
result := Format(’%0x’, [N]);
END;