自定义字节大小?
那么,您知道 char 类型的原语如何具有 1 个字节的大小吗?我如何制作具有自定义尺寸的基元?因此,我制作了一个大小为 16 字节的 int,而不是大小为 4 字节的 int。 有办法做到这一点吗?有办法解决吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这取决于你为什么这样做。通常,您不能使用小于 8 位的类型,因为这是体系结构的可寻址单元。但是,您可以使用结构来定义不同的长度:
但是,不能保证结构的长度为 24 位。此外,这可能会导致字节序问题。在可能的情况下,最好使用与系统无关的类型,例如 uint16_t 等。您还可以使用按位运算符和位移位来非常具体地调整事物。
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:
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.
通常,您只需创建一个表示您感兴趣的数据的结构。如果它是 16 字节的数据,则它要么是多个较小类型的聚合,要么您正在使用具有本机 16 字节整数类型的处理器。
如果您尝试表示极大的数字,则可能需要找到一个可以处理任意大小的数字的特殊库。
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.
在C++11中,有一个很好的解决方案:std::aligned_storage。
它允许您在堆栈上声明一个未初始化的存储块。
In C++11, there is an excellent solution for this: std::aligned_storage.
It allows you to declare a block of uninitialized storage on the stack.
如果你想创建一个新类型,请 typedef 它。如果您希望它的大小为 16 字节,请 typedef 一个其中包含 16 字节成员数据的结构。请注意,编译器通常会根据您的系统调整需求来填充一些东西。 1 字节结构很少会在不小心的情况下保持 1 字节。
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.
您可以仅在 std::string 之间进行静态转换。我对 C++ 的了解不够多,无法举个例子,但我认为这会非常直观。
You could just static cast to and from std::string. I don't know enough C++ to give an example, but I think this would be pretty intuitive.