在 8 位块中处理变量的好方法是什么?
我正在尝试我的玩具语言设计,但遇到了一些问题。我希望它具有以位长度指定的变量。因此,例如,可以这样声明变量:
byte value;
two_bytes value;
现在,这是我的问题。我正在尝试为 C(或 C++)语言创建一个解释器。我对 C/C++ 的理解是,它们的变量类型保证至少为最小大小,但它们可以更大(即,字符至少为 8 位,但某些实现将具有 16 位字符)。
如何用 C/C++ 编写一个只处理特定长度位的解释器?是拥有布尔数组或为 char 类型设置位字段的唯一方法吗?
I'm playing around with a toy language design of mine and I have a few problems. I would like it to have variables specified in bit length. So, for example, one declares the variables like so:
byte value;
two_bytes value;
Now, here's my problem. I'm trying to make an interpreter for the language in C (or C++). My understanding of C/C++ is that their variable types are guaranteed to be at least a minimum size, but they can be larger (ie, a char will be at least 8 bits, but some implementations will have a 16 bit char).
How can I write an interpreter in C/C++ that deals only with specific lengths of bits? Is the only way to have an array of booleans or to set up bitfields for something like the char type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
stdint 标头是您所需要的:
stdint header is what you need:
如果我猜对了,
可能是你的出路……
If I get you right,
could be your way to go...
如果您想要原始类型,那么大多数编译器应该提供
(或
),其中包含诸如uint8_t
之类的类型代码>、<代码>uint16_t、<代码>uint32_t。如果您想要模糊的尺寸(例如
uint13_t
),您可能最好使用更大的标准尺寸。如果您需要节省空间,您可以查看 std::bitset,但这对于大多数操作来说可能会慢得多。If you want primitive types, then most compilers should offer
<stdint.h>
(or<cstdint>
), which contains types such asuint8_t
,uint16_t
,uint32_t
.If you want obscure sizes (like e.g.
uint13_t
), you're probably best just using a larger standard size. If you need to save space, you might look intostd::bitset
, but this will probably be substantially slower for most operations.通常,您可以使用 unsigned int 来保存 8 位之类的内容,并且仍然对其使用按位运算符,例如移位 (>>)。控制长度只是某种插入逻辑。 8 位不能大于 2^8th - 1 (255)。
Usually you can use an unsigned int to hold something of say, 8 bits, and still use bitwise operators on it such as shifting (>>). Controlling the length would simply be some sort of inserted logic. 8 bits can be no larger than 2^8th - 1 (255).
如果您不确定现有的位长度,并希望将其传递到另一个值来解析它,您可以简单地执行以下操作:
现在您可以根据长度访问 a 的组件,最多可达最大大小32 位,虽然 char 永远不会是 32 位,但我只是为了举例而使用它。
If you're unsure of the existing bit length, and want to pass it into another value to parse it as such, you can simply do the following:
Now you can access the components of a depending on the length, up to a maximum size of 32 bits, though a char is never going to be 32 bits, I'm just using it for examples sake.