Convert decimal number to binary string

Ideas and tips for enhancing your TM1 application
Post Reply
rmackenzie
MVP
Posts: 733
Joined: Wed May 14, 2008 11:06 pm

Convert decimal number to binary string

Post by rmackenzie » Sun Oct 12, 2014 10:58 pm

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 );
Robin Mackenzie

Post Reply