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;
    BT   Num, BitNum
    SETC al

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;
  if Value then
    Result := '0' else
    Result := '1';

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

Example of usage
and the result should be
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)