如何以二进制形式获取位(…)数据类型列的值?

时间:2022-05-14 16:24:41

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?

如你所见,最终结果是5。我想要得到一个字符串的值,比如这个0000000101。我怎么做呢?

2 个解决方案

#1


3  

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

您可以使用decbin()函数和sprintf来预挂0

<?php

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

Output:

输出:

0000000101

From your comments:

从你的评论:

12 - 0000001100
26 - 0000011010

Update1:

Update1:

You can assign to $numb variable like this:

你可以分配给$numb variable如下:

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

#2


3  

This is completely using SQL as you requested:

完全按照您的要求使用SQL:

Using CONV() and LPAD():

使用CONV()和LPAD():

LPAD(CONV(id,10,2),10,0)

Here is SQLFiddle for you

这里是SQLFiddle

#1


3  

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

您可以使用decbin()函数和sprintf来预挂0

<?php

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

Output:

输出:

0000000101

From your comments:

从你的评论:

12 - 0000001100
26 - 0000011010

Update1:

Update1:

You can assign to $numb variable like this:

你可以分配给$numb variable如下:

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

#2


3  

This is completely using SQL as you requested:

完全按照您的要求使用SQL:

Using CONV() and LPAD():

使用CONV()和LPAD():

LPAD(CONV(id,10,2),10,0)

Here is SQLFiddle for you

这里是SQLFiddle