Converting Bytes to Bits

From QB64 Wiki
Revision as of 01:51, 26 January 2013 by imported>Clippy
Jump to navigation Jump to search

Although QB64 has _BYTE and _BIT variable types, there may be times that you just want to know which bits are on of off in the byte value or convert the value to a Binary number.

Bits are numbered from 0 to 7 and normally are read from the most significant bit(MSB = 7) to the least significant bit(LSB = 0).

The following example shows how to convert an _UNSIGNED _BYTE or INTEGER value(0 to 255) to a Binary STRING number in Qbasic.

DIM byte as _UNSIGNED _BYTE byte = 222 FOR bit = 7 to 0 STEP -1 IF byte AND 2 ^ bit THEN PRINT "1"; ELSE PRINT "0"; NEXT

Notes: The above code can be adapted to place a value into a bit Array for up to 8 flag values in a single Byte.

See also:

Keyword Reference - Alphabetical
Keyword Reference - By Usage
Main Wiki Page