How to get the value of the columns of the BIT data type (...) in binary form?

advertisements

I have a table like this:

// numbers
+---------+------------+
|    id   |    numb    |
+---------+------------+
| int(11) |   bit(10)  |
+---------+------------+
| 1       | 0000000001 |
| 2       | 0000000101 |
| 3       | 0000000000 |
| 4       | 0000001011 |
+---------+------------+

When I fetch numb column, the result will be like this:

// Query
mysql> SELECT numb FROM numbers WHERE id = 2

// Fetching by PHP (pdo)
$result = $stm->fetch();
$numb   = $result['numb'];
echo $numb;
//=> 5

As you see, the final result is 5. While I want to get that exact value as a string, like this 0000000101. How can I do that?


You can use decbin() function and sprintf for pre-pending zeros

<?php

$numb = 5;
echo sprintf("%010d",decbin($numb));

Output:

0000000101

From your comments:

12 - 0000001100
26 - 0000011010

Update1:

You can assign to $numb variable like this:

$numb = sprintf("%010d",decbin($result['numb']));