Expand/Shrink

int_to_bits

Definition: sequence s = int_to_bits(atom x, integer nbits=0)
Description: Return the low-order nbits bits of x, as a sequence of 1s and 0s.
If nbits is 0/omitted, then a must be a non-negative integer, and the minimum number of bits to represent a are returned, which will be at most 30 on 32-bit and 62 on 64-bit (1 less because that’s phix for you, and 1 less because the sign bit is 0).

The least significant bits come first.
pwa/p2js: Supported.
Comments: You can use subscripting, slicing, and/or/xor/not of entire sequences etc. to manipulate sequences of bits.

Shifting of bits and rotating of bits are easy to perform.

For negative numbers the twos complement bit pattern is returned.

While positive numbers could, in theory, yield only as many bits as are set, in contrast negative numbers left to the same device would produce an infinite stream of trailing 1s. It is for this reason that you must always specify the required number of bits, typically a multiple of 8, but anything from 1 to 53 (on 32-bit, or 64 on 64-bit) is perfectly fine - of course for bit-fields you probably want the exact number of flags it holds.
Example:
s = int_to_bits(177, 8) -- (177==0b10110001, ie 128+[0*64]+32+16+[0*8,4,2]+1)
-- s is {1,0,0,0,1,1,0,1} -- note the "reverse" order, lsb first
s = int_to_bits(19, 8)  -- (19==0b00010011, ie 16+[0*8+0*4]+2+1)
-- s is {1,1,0,0,1,0,0,0} -- note the "reverse" order, lsb first
s = int_to_bits(19)
-- s is {1,1,0,0,1}
Implementation: See builtins\machine.e (an autoinclude) for details of the actual implementation.
See Also: bits_to_int, and_bits, or_bits, xor_bits, not_bits, sequence operations