Tuesday, September 29, 2009

Get integer bits

Did you ever needed/wanted to see an integer as 0's and 1's I mean in binary form? I'm more than sure you did/do, here is a method to see if a bit of an integer variable is ON or OFF
function GetBitState(Num, BitNum: Cardinal): Boolean;
asm
    BT   Num, BitNum
    SETC al
end;

The above function returns True if bit is ON and False if bit is OFF, now let's use this function to get a 32 char string so we can see how what's the binary form of a integer, before the actual function we need an intermediate function which translates True and False into 0 and 1 char
function BoolToChar(Value: Boolean): Char;
begin
  if Value then
    Result := '0' else
    Result := '1';
end;

now all we need the function which translates an integer to a "string of bits"
function GetIntBits(Value: Integer): String;
var
  index: Integer;
begin
  SetLength(Result, 32);
  for index := 0 to 31 do
    Result[index +1] := BoolToChar(GetBitState(Value, index));
end;

Example of usage
ShowMessage(GetIntBits(2009));
and the result should be
01100100000111111111111111111111
I can think of only two things(right now...) that would make this methods useful:
a) some sort of compression method
b) some sort of encryption algorithm

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)