Page 1 of 1

Convert decimal number to binary string

Posted: Sun Oct 12, 2014 10:58 pm
by rmackenzie
Here is a bit of code to take a decimal number and return a string containing the equivalent binary value. I found this useful when needing to read a flag value stored as a bit.

Code: Select all

# max value to be converted 
# from decimal to binary
# is 4294967295, i.e. 2^31
nInputValue = 4294967295;
nRunningValue = nInputValue;
sBinaryValue = '';
nBitCounter = 31;
WHILE ( nBitCounter >= 0 );
  nPowerOf2 = 2 ^ nBitCounter;
  IF ( nRunningValue >= nPowerOf2 );
    sBit = '1';
    nRunningValue = nRunningValue - nPowerOf2;
  ELSE;
    sBit = '0';
  ENDIF;
  sBinaryValue = sBinaryValue | sBit;
  nBitCounter = nBitCounter - 1;
END;

# test result
AsciiOutput ( 'test.txt', sBinaryValue );