Custom byte size?

妖精的绣舞 提交于 2019-12-05 08:57:50

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.

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.

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.

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.

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