Sumit
Sumit

Reputation: 2264

Bitwise AND/OR with a varbinary(255) in mysql

I have the following field in a mysql table:

bitmap  varbinary(256)

I want perform a bitwise AND on this field. I tried:

select id, Hex(bitmap) from mytable;
| 735 | 1D1BA8284000000000000000000000000000000000000000000000000000000000 |
| 736 | 1D1BACA80000000000000000000000000000000000000000000000000000000000 |

select Hex(bitmap & 0xFFFFFFFFF000000000000000000000000000000000000000000000000000000000) from mytable

| 735 | 0                                                                                       |
| 736 | 0                                                                                       |

Mysql always give 0 even then my columns are non-zero

Upvotes: 2

Views: 2257

Answers (1)

Alnitak
Alnitak

Reputation: 339816

MySQL doesn't support bitwise operations on whole varbinary() fields.

From the manual:

MySQL uses BIGINT (64-bit) arithmetic for bit operations, so these operators have a maximum range of 64 bits.

You might be able to perform operations on single bytes at a time by extracting them with substr() and then concat that result with the remaining bytes that originally wrapped the byte of interest, i.e.

SELECT CHAR(ASCII(SUBSTR(bitmap, 1, 1)) & 0xff || SUBSTR(bitmap, 2)

obviously this doesn't scale well...

Upvotes: 4

Related Questions