如何破解这个位域?
我必须编写一个函数 setbits(x,p,n,y)
,它返回 x
以及从位置 n
位开始>p 设置为无符号字符变量 y
最右边的 n
位(保持其他位不变)。
例如,如果x = 10101010(十进制170)
和y = 10100111(十进制167)
和n = 3
和p = 6< /code> 假设你需要去掉 3 位 y (111) 并将它们放入
x
的位置 10xxx010
才能得到答案 <代码>10111010。
该函数应以二进制形式打印结果。
输出应该是这样的:
x = 10101010 (binary)
y = 10100111 (binary)
setbits n = 3, p = 6 gives x = 10111010 (binary)
嗨,我在位字段中遇到了这个问题。
我该怎么办?
Typedef struct {
unsigned char x:8;
unsigned char y:8;
} var;
I have to write a function setbits(x,p,n,y)
who returns x
with the n
bits that begin at position p
set to the right most n
bits of an unsigned char variable y
(leaving other bits unchanged).
E.g. if x = 10101010 (170 decimal)
and y = 10100111 (167 decimal)
and n = 3
and p = 6
say then you need to strip off 3 bits of y (111)
and put them in x
at position 10xxx010
to get answer 10111010
.
This function should print out the result in binary form.
The output should be like this :
x = 10101010 (binary)
y = 10100111 (binary)
setbits n = 3, p = 6 gives x = 10111010 (binary)
Hi I came across this problem in bit field.
How should I go about it?
Typedef struct {
unsigned char x:8;
unsigned char y:8;
} var;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
位域是一个特定的 C 发明,与此无关。例如,您可以使用
16 位结构,其中包含 3 个组件,每个组件都小于一个字节。然而,C 标准没有提及它们的相对位置。您不能假设它们在内存中的布局为
RRRRRGGGGGGBBBBB
。此外,位字段宽度是恒定的,在您的情况下,所需的位是可变的。因此,谷歌搜索“C 位字段”不会帮助您解决这个问题。至于你的问题,你应该知道
x & binary(11000011)
将中间 4 位清零,并且 y | binary(00111100) 将中间 4 位设置为 1。Bitfields are a specific C invention that have nothing to do with this. For instance, you could have
which is a 16 bits structure, with 3 components that are each smaller than a byte. However, the C standard say nothing about their relative position. You can't assume that they're laid out in memory as
RRRRRGGGGGGBBBBB
. Furthermore, the bitfieldwidths are constant, and in your case the bits needed are variable. So, googling for "C bitfields" won't help you with this problem.As for your problem, you should know that
x & binary(11000011)
zeroes out the middle 4 bits, andy | binary(00111100)
sets the middle 4 bits to one.char 不是位字段允许的类型,它们必须是 int 类型。如果您使用 char,则将调用 C 标准未涵盖的实现定义的行为(请参阅 ISO 9899:1999 6.7.2.1 §4)。
因此,如果不知道您正在使用什么系统和编译器,就不可能回答您的问题。
char is not an allowed type for bit fields, they must be of type int. If you use char, you are invoking implementation-defined behaviour not covered by the C standard (see ISO 9899:1999 6.7.2.1 §4).
Thus your question is impossible to answer without knowing what system and compiler you are using.
t = y<<(8-n)
k = t>>p;
打印 x&k;
假设每个比特流是8位。
t = y<<(8-n)
k = t>>p;
print x&k;
Assuming each bit stream is 8 bits.