简体   繁体   English

查看十六进制数的特定位?

[英]View a specific bit of a hex number?

I am working on a piece of logic that will teach me how bitops and bit manipulation works, and I am trying to view a specific bit of a given hex number.我正在研究一段逻辑,它将教我 bitops 和位操作如何工作,并且我正在尝试查看给定十六进制数的特定位。 For example f0f0 has the following bit value 1111000011110000. So let's say I am trying to view the i^th bit, let's say for example i choose the 4th position, my logic should return 1. I tried doing it by doing this logic:例如 f0f0 具有以下位值 1111000011110000。所以假设我正在尝试查看第 i^ 位,例如我选择第 4 个位置,我的逻辑应该返回 1。我尝试通过执行以下逻辑来做到这一点:

unsigned int desiredBit = hex & (1 << decimal);
      printf("%x\n", desiredBit);

This seems to work any time a bit is 0, but whenever a bit is 1, it spits out a multiple of 10. I assumed that doing a << would just take me to that position but i guess I was wrong.这似乎在任何时候都是 0 的时候起作用,但是只要是 1,它就会吐出 10 的倍数。我认为执行<<只会带我到那个位置,但我想我错了。 Any guidance on how to fix my logic?关于如何解决我的逻辑的任何指导?

You are getting a multiple of 2 actually, ie the "weight" of this particular bit if it is set, 0 otherwise.您实际上得到的是 2 的倍数,即如果设置了这个特定位的“权重”,否则为 0。 If you just want to know if it is set or not, check if this weight is something != 0 or not:如果您只想知道它是否已设置,请检查此权重是否为 != 0:

Try尝试

unsigned int setOrNot = (hex & (1 << decimal)) != 0;

You're getting the numerical value of the number with just that one that bit set, which isn't exactly 1 unless it's the LSB.你得到的数字的数值只设置了那个位,除非它是 LSB,否则它不完全是1

For example, with the number 0b11100101 , if you mask out the second-MSB ( 0b11100101 & 0b01000000 ), the result is 0b01000000 which is 64 in base 10.例如,对于数字0b11100101 ,如果您屏蔽第二个 MSB( 0b11100101 & 0b01000000 ),结果是0b01000000 ,它是基数 10 中的 64。

If you want the result to be either 1 or 0 , you can perform !!如果您希望结果为10 ,则可以执行!! on the entire operation, ie printf("%d\\n", !!(num1 & num2));在整个操作上,即printf("%d\\n", !!(num1 & num2)); will always either be 1 if the bit was set or 0 if it was not.如果该位已设置,则将始终为1否则将始终为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM