开发者

how do i define 24 bit array in c++?

开发者 https://www.devze.com 2023-01-11 03:13 出处:网络
how do i define 24 bit array in c++? (variable declaratio开发者_如何转开发n)There is no 24-bit variable type in C++.

how do i define 24 bit array in c++? (variable declaratio开发者_如何转开发n)


There is no 24-bit variable type in C++.

You can use a bitpacked struct:

struct ThreeBytes {
    uint32_t value:24;
};

But it is not guaranteed that sizeof ThreeBytes == 3.

You can also just use uint32_t or sint32_t, depending on what you need.

Another choice is to use std::bitset:

typedef std::bitset<24> ThreeBytes;

Then make an array out of that:

ThreeBytes *myArray = new ThreeBytes[10];

Of course, if you really just need "three bytes", you can make an array of arrays:

typedef uint8_t ThreeBytes[3];

Note that uint8_t and friends are non-standard, and are used simply for clarification.


An unsigned byte array of 3 bytes is 24 bits. Depending on how you are planning to use it, it could do.

unsigned char arrayname[3]

As @GMan points out you should be aware that it's not 100% of all systems that has 8 bits chars.


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 an int 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 ints or longs (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.


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.


Use bitset or bitvector if they are supported on your platform. (They are :) )


std::vector<std::bitset<24> > myArray;
0

精彩评论

暂无评论...
验证码 换一张
取 消