Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to bitset?

is there any possibility of converting string like '1101' to its BIT(4) equivalent in MySQL? I have checked CONVERT/CAST functions but they do not allow to do so.

Thanks!

like image 546
Jacek Francuz Avatar asked Oct 21 '22 03:10

Jacek Francuz


1 Answers

You can use CONV()

CONV('1100', 2, 10) * 1

or Bit-Field Literals

e.g.

CREATE TABLE Table1 (bit_value BIT(4));

INSERT INTO Table1 VALUES (CONV('1100', 2, 10) * 1);
INSERT INTO Table1 VALUES (b'1101');

SELECT bit_value, 
       BIN(bit_value) bin_representation
  FROM Table1

Output:

| BIT_VALUE | BIN_REPRESENTATION |
----------------------------------
|        12 |               1100 |
|        13 |               1101 |

Here is SQLFiddle demo

like image 141
peterm Avatar answered Oct 23 '22 19:10

peterm