如何设置整数的前三个字节?在C ++中 [英] How to set first three bytes of integer? in C++

查看:85
本文介绍了如何设置整数的前三个字节?在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中将整数的前三个字节设置为0.我尝试了这段代码,但是我的整数变量a并没有改变,输出始终为-63.我在做什么错了?

I want to set first three bytes of an integer to 0 in C++. I tried this code, but my integer variable a is not changing, output is always -63. What am I doing wrong?

#include <iostream>
#include <string>

int main()
{
  int a = 4294967233;
  std::cout << a << std::endl;
  for(int i = 0; i< 24; i++)
    {
        a |= (0 << (i+8));
        std::cout <<  a << std::endl;
    }

}

推荐答案

只需使用按位和(&)带掩码,就没有循环的理由:

Just use bitwise and (&) with a mask, there is no reason for loop:

a &= 0xFF000000; // Drops all but the third lowest byte
a &= 0x000000FF; // Drops all but the lowest byte

(感谢@JSF进行更正)

(Thanks to @JSF for the corrections)

如@black所述,您可以使用数字分隔符,因为C ++ 14,以使您的代码更具可读性:

As noted by @black, you may use Digit separators since C++14 in order to make your code more readable:

a &= 0xFF'00'00'00; // Drops all but the third lowest byte
a &= 0x00'00'00'FF; // Drops all but the lowest byte

这篇关于如何设置整数的前三个字节?在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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