前往:位域和位打包 [英] Go: Bitfields and bit packing
问题描述
C语言的位域提供了一种非常方便的方法来定义结构中的任意宽度的字段(请不要在一分钟内考虑可移植性的问题.)例如,这是一个具有几个字段和一个标志"的简单结构:/p>
The C language's bitfields provide a fairly convenient method of defining arbitrary-width fields within a structure (nevermind the problems with portability for a minute.) For example, here's a simple structure with a couple fields and a 'flag':
#pragma pack(push,1)
struct my_chunk{
unsigned short fieldA: 16;
unsigned short fieldB: 15;
unsigned short fieldC: 1;
};
#pragma pop()
添加#pragma语句会将这种结构打包成一个32位字(例如,确保对 my_chunk
指针的指针操作进行对齐,并节省空间).
Adding the #pragma statements packs this structure into a 32-bit word (ensuring that pointer manipulations of my_chunk
pointers are aligned, for example, along with space savings).
从语法上来说,访问每个字段非常好:
Accessing each field is syntactically very nice:
struct my_chunk aChunk;
aChunk.fieldA = 3;
aChunk.fieldB = 2;
aChunk.fieldC = 1;
在没有该语言帮助的情况下执行此操作的另一种方法非常丑陋,并且几乎都转移到了汇编程序中.例如一种解决方案是为要访问的每个字段都提供位移位宏:
The alternate way of doing this without the language's help is rather ugly and pretty much devolves into assembler. e.g. one solution is to have bitshift macros for each field you want to access:
#define FIELD_A 0xFF00
#define FIELD_B 0x00FE
#define FIELD_C 0x0001
#define get_field(p, f) ((*p)&f)
#define set_field(p, f, v) (*p) = (v<<f) + (*p)&(~f)
...
set_field(&my_chunk, FIELD_A, 12345);
..或类似的内容(有关更多形式,请查看此)
.. or something roughly like that (for more formality, take a look at this)
所以问题是,如果我想在go中做"位域,这样做的最佳实践是什么?
So the question is, if I want to "do" bitfields in go, what is the best practice for doing so?
推荐答案
您可以编写Go软件包来执行此操作;不需要汇编程序.
You could write a Go package to do this; no assembler is required.
这篇关于前往:位域和位打包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!