User Byte Size?

So, you know how a char primitive is 1 byte in size? How do I make a primitive with a custom size? So, instead of going into an int with a size of 4 bytes, I am doing one with a size of, say, 16. Is there a way to do this? Is there any way around this?

+6
c ++ sizeof byte primitive size
source share
4 answers

Usually, you simply create a structure that represents the data in which you are interested. If it is 16 bytes of data, or it is a combination of several smaller types, or you are working on a processor that has its own 16-byte integral type.

If you are trying to imagine extremely large numbers, you may need to find a special library that processes numbers of arbitrary size.

+5
source share

It depends on why you are doing this. Typically, you cannot use types less than 8 bits because this is the address unit for the architecture. However, you can use structures to define different lengths:

struct s { unsigned int a : 4; // a is 4 bits unsigned int b : 4; // b is 4 bits unsigned int c : 16; // c is 16 bits }; 

However, there is no guarantee that the structure will be 24 bits long. In addition, this can lead to problems from the side. Where you can, it is best to use system independent types like uint16_t etc. You can also use bitwise operators and bit shifts to deceive things very much.

+4
source share

In C ++ 11 there is a great solution for this: std :: aligned_storage.

 #include <memory> #include <type_traits> int main() { typedef typename std::aligned_storage<sizeof(int)>::type memory_type; memory_type i; reinterpret_cast<int&>(i) = 5; std::cout << reinterpret_cast<int&>(i) << std::endl; return 0; } 

It allows you to declare a block of uninitialized storage on the stack.

+1
source share

If you want to create a new type, enter it. If you want the size to be 16 bytes, enter a typedef structure containing 16 bytes of element data inside it. Just beware that often compilers will do everything to fit your needs for system alignment. A 1 byte structure rarely remains without a 1 byte byte.

0
source share

All Articles