如何在 c++ 中定义 24 位数组?
我如何在C++中定义24位数组? (变量声明)
how do i define 24 bit array in c++? (variable declaration)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我如何在C++中定义24位数组? (变量声明)
how do i define 24 bit array in c++? (variable declaration)
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(6)
C++ 中没有 24 位变量类型。
您可以使用位打包结构:
但不能保证
sizeof ThreeBytes == 3
。您也可以仅使用
uint32_t
或sint32_t
,具体取决于您的需要。另一种选择是使用
std::bitset
:然后从中创建一个数组:
当然,如果您确实只需要“三个字节”,则可以创建一个数组数组:
注意
uint8_t
和朋友是非标准的,仅用于澄清。There is no 24-bit variable type in C++.
You can use a bitpacked struct:
But it is not guaranteed that
sizeof ThreeBytes == 3
.You can also just use
uint32_t
orsint32_t
, depending on what you need.Another choice is to use
std::bitset
:Then make an array out of that:
Of course, if you really just need "three bytes", you can make an array of arrays:
Note that
uint8_t
and friends are non-standard, and are used simply for clarification.3 个字节的无符号字节数组为 24 位。根据您计划如何使用它,它可以做到。
正如 @GMan 指出的那样,您应该意识到这并不是所有系统的 100% 有 8 位字符。
An unsigned byte array of 3 bytes is 24 bits. Depending on how you are planning to use it, it could do.
As @GMan points out you should be aware that it's not 100% of all systems that has 8 bits chars.
如果您打算对它们执行按位运算,则只需使用至少 24 位的整型即可。
int
在大多数平台上都是 32 位,因此int
可能适合此目的。编辑:由于您实际上想要一个 24 位变量的数组,因此最简单的方法是创建一个
int
或long
(只要它是至少包含 24 位的整数数据类型)并将每个元素视为 24 位。If you intend to perform bitwise operations on them, then simply use an integral type that has at least 24 bits. An
int
is 32 bits on most platforms, so anint
may be suitable for this purpose.EDIT: Since you actually wanted an array of 24 bit variables, the most straightforward way to do this is to create an array of
int
s orlong
s (as long as it's an integral data type that contains at least 24 bits) and treat each element as though it was 24 bits.根据您的目的(例如,如果您担心使用 32 位类型可能会浪费太多内存),您还可以考虑创建一个长度为三倍的字节数组。
我以前经常这样做来存储 RGB 图像。要访问第 n 个元素,您必须乘以三,然后添加零、一或二,具体取决于您想要的元素的“通道”。当然,如果您想将所有 24 位作为一个整数进行访问,这种方法需要一些额外的算术。
因此,只需
unsigned char myArray[ELEMENTS * 3];
,其中 ELEMENTS 是您想要的 24 位元素的数量。Depending on your purpose (for example, if you are concerned that using a 32bit type might waste too much memory), you might also consider creating an array of bytes with three times the length.
I used to do that a lot for storing RGB images. To access the n'th element, you would have to multiply by three and then add zero, one or two depending on which "channel" out of the element you wanted. Of course, if you want to access all 24 bits as one integer, this approach requires some additional arithmetics.
So simply
unsigned char myArray[ELEMENTS * 3];
where ELEMENTS is the number of 24bit elements that you want.使用 bitset 或 bitvector(如果您的平台支持)。 (他们是:))
Use bitset or bitvector if they are supported on your platform. (They are :) )