Bit-field values can be written using
b'
or
value
'0b
notation.
value
value
is a binary value written using
zeros and ones.
Bit-field notation is convenient for specifying values to be
assigned to BIT
columns:
mysql>CREATE TABLE t (b BIT(8));
mysql>INSERT INTO t SET b = b'11111111';
mysql>INSERT INTO t SET b = b'1010';
mysql>INSERT INTO t SET b = b'0101';
Bit values are returned as binary values. To display them in
printable form, add 0 or use a conversion function such as
BIN()
. High-order 0 bits are not
displayed in the converted value.
mysql> SELECT b+0, BIN(b+0), OCT(b+0), HEX(b+0) FROM t;
+------+----------+----------+----------+
| b+0 | BIN(b+0) | OCT(b+0) | HEX(b+0) |
+------+----------+----------+----------+
| 255 | 11111111 | 377 | FF |
| 10 | 1010 | 12 | A |
| 5 | 101 | 5 | 5 |
+------+----------+----------+----------+
Bit values assigned to user variables are treated as binary
strings. To assign a bit value as a number to a user variable,
use CAST()
or
+0
:
mysql>SET @v1 = 0b1000001;
mysql>SET @v2 = CAST(0b1000001 AS UNSIGNED), @v3 = 0b1000001+0;
mysql>SELECT @v1, @v2, @v3;
+------+------+------+ | @v1 | @v2 | @v3 | +------+------+------+ | A | 65 | 65 | +------+------+------+
User Comments
mysql> INSERT INTO t SET b = b'0101';
3 rows in set (0.00 sec)Query OK, 1 row affected (0.03 sec)
mysql> select b+0, BIN(b+0), OCT(b+0), HEX(b+0) from t;
Notice the result and way to get the shown table. also notice 0101 is shown in BINARY as 101 and not 0101.
If you're loading binary flags into a BIT(1) field from a text file using LOAD DATA INFILE, note that ordinary zeros are loaded as "b'1'", which is probably not what you intended. If you want these fields to load as BIT zeros, then you have to convert the zero values to "b'0'" in the input file.
I'm not sure if that's a bug or expected behavior. I mean, zero is zero -- even in binary -- but ASCII "0" is byte #48, which is certainly a lot bigger than binary "1". You don't see the loader converting integer numbers like "21" to their ASCII equivalents (50*256 + 49 = 12849) when loading them into an integer field, though, so I would argue that the behavior is a "bit" unexpected. (pardon the pun)
Add your own comment.