存储由 0 和 1 组成的长数字的最佳数据类型 [英] Best datatype to store a long number made of 0 and 1

查看:76
本文介绍了存储由 0 和 1 组成的长数字的最佳数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道存储这些的最佳数据类型是什么:

I want to know what's the best datatype to store these:

  • null
  • 0
  • /* 其他数字的长度总是 7 位 */
  • 0000000
  • 0000001
  • 0000010
  • 0000011
  • /* 等等 */
  • 1111111

我已经测试过,INT 也能正常工作.但是有更好的数据类型.因为我所有的数字都是由 01 数字组成的.有没有更好的数据类型?

I have tested, INT works as well. But there is a better datatype. Because all my numbers are made of 0 or 1 digits. Is there any better datatype?

推荐答案

您显示的是二进制数

  • 0000000 = 0
  • 0000001 = 2^0 = 1
  • 0000010 = 2^1 = 2
  • 0000011 = 2^0 + 2^1 = 3

因此,只需将这些数字存储在整数数据类型中(当然,它在内部存储为位,如图所示).您可以为此使用 BIGINT,如按位运算的文档中所推荐的 (http://dev.mysql.com/doc/refman/5.7/en/bit-functions.html).

So simply store these numbers in an integer data type (which is internally stored with bits as shown of course). You could use BIGINT for this, as recommended in the docs for bitwise operations (http://dev.mysql.com/doc/refman/5.7/en/bit-functions.html).

这里是如何设置标志n:

Here is how to set flag n:

UPDATE mytable
SET bitmask = POW(2, n-1)
WHERE id = 12345;

以下是添加标志的方法:

Here is how to add a flag:

UPDATE mytable
SET bitmask = bitmask | POW(2, n-1)
WHERE id = 12345;

以下是检查标志的方法:

Here is how to check a flag:

SELECT *
FROM mytable
WHERE bitmask & POW(2, n-1)

但正如评论中提到的:在关系数据库中,您通常使用列和表来显示属性和关系,而不是编码的标志列表.

But as mentioned in the comments: In a relational database you usually use columns and tables to show attributes and relations rather than an encoded flag list.

这篇关于存储由 0 和 1 组成的长数字的最佳数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆