Custom byte size?

旧街凉风 提交于 2019-12-07 03:48:09

问题


So, you know how the primitive of type char has the size of 1 byte? How would I make a primitive with a custom size? So like instead of an in int with the size of 4 bytes I make one with size of lets say 16. Is there a way to do this? Is there a way around it?


回答1:


Normally you'd just make a struct that represents the data in which you're interested. If it's 16 bytes of data, either it's an aggregate of a number of smaller types or you're working on a processor that has a native 16-byte integral type.

If you're trying to represent extremely large numbers, you may need to find a special library that handles arbitrarily-sized numbers.




回答2:


It depends on why you are doing this. Usually, you can't use types of less than 8 bits, because that is the addressable unit for the architecture. You can use structs, however, 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 struct will be 24 bits long. Also, this can cause endian issues. Where you can, it's best to use system independent types, such as uint16_t, etc. You can also use bitwise operators and bit shifts to twiddle things very specifically.




回答3:


In C++11, there is an excellent 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.




回答4:


If you want to make a new type, typedef it. If you want it to be 16-bytes in size, typedef a struct that has 16-bytes of member data within it. Just beware that quite often compilers will pad things on you to match your systems alignment needs. A 1 byte struct rarely remains 1 bytes without care.



来源:https://stackoverflow.com/questions/2679801/custom-byte-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!