设置十六进制数的位数
如何设置十六进制数字? 我目前有这样的代码:
int row = 0x00000000;
row |= 0x3 << 8;
row |= 0x2 << 4;
row |= 0x1 << 0;
printf("Row: 0x%08x", row);
只要“行”只是零,它就可以完美地工作。一旦我将其更改为这样的内容:
int row = 0x33333333;
row |= 0x3 << 8;
row |= 0x2 << 4;
row |= 0x1 << 0;
printf("Row: 0x%08x", row);
我就会得到以下输出:
行:0x33333333
How can I set a digit in a hexadecimal number?
I currently have this code:
int row = 0x00000000;
row |= 0x3 << 8;
row |= 0x2 << 4;
row |= 0x1 << 0;
printf("Row: 0x%08x", row);
Which works perfectly fine as long as "row" is just zeros. As soon as I change it to something like this:
int row = 0x33333333;
row |= 0x3 << 8;
row |= 0x2 << 4;
row |= 0x1 << 0;
printf("Row: 0x%08x", row);
I just get this output:
Row: 0x33333333
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该先删除(使其为 0)该数字。
~
运算符反转数字中所有位的值。所以。0x000000f0
变为0xffffff0f
。您的代码应如下所示:
You should delete (make it 0) the digit first.
~
operator reverses the values of all bits in the number. So.0x000000f0
becomes0xffffff0f
.Your code should look like:
正如 Alexandru 所解释的,您确实需要先清除要设置的位字段,然后再继续设置它。
只是为了进一步说明为什么您的代码没有执行您想要的操作,请考虑二进制级别的变量发生了什么:
|= 运算符是“按位或”。因此,如果您尝试设置的位或您传入的位设置为 1,则结果为 1。在您的代码中,row 设置为 0x33333333,因此每 4 位十六进制数字是二进制的0011。当您使用0x2进行按位或操作时,您会得到0x3:
如果您首先清除位字段,您会得到0x2,这就是您想要的:
请注意,使用移位和按位运算进行数据操作不太可能是可移植的不同平台之间。尝试在不同字节顺序的机器上运行依赖于位移位的代码时,或者实际上,如果尝试在 64 位机器上运行可在 32 位机器上运行的代码,您可能会遇到问题:
http://www.viva64.com/en/a/0004/#ID0EQFDI
维基百科有更多关于按位运算的信息:
< a href="http://en.wikipedia.org/wiki/Bitwise_operation" rel="nofollow">http://en.wikipedia.org/wiki/Bitwise_operation
As Alexandru explained, you do need to clear the bitfield you're trying to set before you go on to set it.
Just to add further comment on why your code didn't do what you wanted, consider what is happening to the variable at the binary level:
The |= operator is a "bitwise or". Hence if either the bit you're trying to set OR the bit you're passing in is set to 1, the result is 1. In your code, row is set to 0x33333333, so each 4 bit hexadecimal digit is 0011 in binary. When you bitwise or that with 0x2, you get 0x3:
If you clear the bitfield first, you get 0x2, which is what you want:
Note that data manipulation using shifts and bitwise operations is unlikely to be portable between different platforms. You may run into problems trying to run code relying on bit shifts on machines of different endianess, or indeed if you try to run code that works on a 32 bit machine on a 64 bit machine:
http://www.viva64.com/en/a/0004/#ID0EQFDI
Wikipedia has more on bitwise operations:
http://en.wikipedia.org/wiki/Bitwise_operation