C位运算中0x01和0x80代表什么? [英] What are 0x01 and 0x80 representative of in C bitwise operations?

查看:350
本文介绍了C位运算中0x01和0x80代表什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反转C中的位顺序(作业问题,主题:按位运算符).我发现这样的解决方案,但我对所使用的十六进制值(0x01和0x80)感到有些困惑.

I'm trying to reverse the order of bits in C (homework question, subject: bitwise operators). I found this solution, but I'm a little confused by the hex values used -- 0x01 and 0x80.

  unsigned char reverse(unsigned char c) {
     int shift;
     unsigned char result = 0;

     for (shift = 0; shift < CHAR_BITS; shift++) {
        if (c & (0x01 << shift))
            result |= (0x80 >> shift);
     }
     return result;
  }

我正在研究的尚未讨论这些价值,因此我不太确定如何构成这些价值.有人可以阐明这个解决方案吗?谢谢!

The book I'm working out of hasn't discussed these kinds of values, so I'm not really sure what to make of them. Can somebody shed some light on this solution? Thank you!

推荐答案

0x01是设置的最低有效位,因此十进制值为1.

0x01 is the least significant bit set, hence the decimal value is 1.

0x80是8位字节集中的最高有效位.如果将其存储在带符号的char中(在使用2的补码表示法的机器上-就像您可能会遇到的大多数机器一样),它是最大的负值(十进制-128);在一个无符号字符中,它是十进制+128.

0x80 is the most significant bit of an 8-bit byte set. If it is stored in a signed char (on a machine that uses 2's-complement notation - as most machines you are likely to come across will), it is the most negative value (decimal -128); in an unsigned char, it is decimal +128.

另一种成为第二性的模式是所有位均已设置的0xFF;对于有符号字符,这是十进制-1;对于无符号字符,这是十进制255.而且,当然是0x00或零,没有设置任何位.

The other pattern that becomes second nature is 0xFF with all bits set; this is decimal -1 for signed characters and 255 for unsigned characters. And, of course, there's 0x00 or zero with no bits set.

循环在第一个周期执行的操作是检查LSB(最低有效位)是否已设置,如果已设置,则在结果中设置MSB(最高有效位).在下一个循环中,它将检查LSB的下一个,并将MSB的下一个设置,等等.

What the loop does on the first cycle is to check if the LSB (least significant bit) is set, and if it is, sets the MSB (most significant bit) in the result. On the next cycle, it checks the next to LSB and sets the next to MSB, etc.

| MSB |     |     |     |     |     |     | LSB |
|  1  |  0  |  1  |  1  |  0  |  0  |  1  |  1  |   Input
|  1  |  1  |  0  |  0  |  1  |  1  |  0  |  1  |   Output
|  1  |  0  |  0  |  0  |  0  |  0  |  0  |  0  |   0x80
|  0  |  0  |  0  |  0  |  0  |  0  |  0  |  1  |   0x01
|  0  |  1  |  0  |  0  |  0  |  0  |  0  |  0  |   (0x80 >> 1)
|  0  |  0  |  0  |  0  |  0  |  0  |  1  |  0  |   (0x01 << 1)

这篇关于C位运算中0x01和0x80代表什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆