BIN$ function

Purpose

Return a string that is the binary (base 2) representation of its argument.

Syntax

s$ = BIN$(numeric_expression [, digits])

Remarks

numeric_expression must be in the range -2,147,483,648 to +2,147,483,647.  Any fractional part of numeric_expression is rounded before the string is created.  If digits is specified, the resulting string will be of length digits.  If the resulting string is longer than digits, the result will be truncated from the left as needed.  If the resulting string is shorter than digits, leading zeros will be added to the left to make the final string digits long.

Thus, for 12959:

0011 0010 1001 1111   ' +12959           

1100 1101 0110 0000   ' reverse all bits

                 +1   ' add 1            

1100 1101 0110 0001   ' -12959            

Due to the use of two's-complement binary form to represent numbers, bit patterns with the most significant bit set to 1 may represent either of two possible values, depending on whether the value is regarded as signed or unsigned.  See Numeric Literals for more information on explicitly casting numeric literal values to specific data types and distinguishing between signed and unsigned values.  Also see the HEX$ function.

For example, the value with 32 binary ones "11111111111111111111111111111111" may be either -1 (signed Long-integer) or 4,294,967,295 (unsigned Double-word).

Note that the binary representation for a negative number is different for numbers that have different bit lengths.  For a regular 16-bit Integer, -1 is represented as 16 binary ones ("1111111111111111").  This corresponds to the unsigned value 65,535.  If you store this value in a 32-bit Long-integer, you would end up with either -1 or 65,535 depending on how you store it.

Binary strings can be converted to numeric values with the VAL function by prefixing the binary string with "&B".  If the string has a leading zero, the result is always unsigned.  For example:

a$ = BIN$(65535)     ' = "1111111111111111"

x& = VAL("&B" + a$)  ' Signed result (-1)

y& = VAL("&B0" + a$) ' Unsigned result (65535)

See also

FORMAT$, HEX$, OCT$, STR$, USING$, VAL