一种反转整数变量的二进制值的方法 [英] A way to invert the binary value of a integer variable

查看:76
本文介绍了一种反转整数变量的二进制值的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个整数 int九= 9; ,其二进制形式为 1001 。是否有一种简单的方法可以将其反转,以便获得 0110

I have this integer int nine = 9; which in binary is 1001. Is there an easy way to invert it so I can get 0110 ?

推荐答案

int notnine = ~nine;

如果仅担心最后一个字节:

If you're worried about only the last byte:

int notnine = ~nine & 0x000000FF;

如果您只对最后一个字节感兴趣:

And if you're only interested in the last nibble:

int notnine = ~nine & 0x0000000F;

~运算符是按位取反,而掩码仅提供您关心的字节/半字节。

The ~ operator is the bitwise negation, while the mask gives you only the byte/nibble you care about.

真正只对最后一个字节感兴趣,最简单的是:

If you truly are interested in only the last nibble, the most simple is:

int notnine = 15 - nine;

对每个小节都有效。 :-)

Works for every nibble. :-)

这篇关于一种反转整数变量的二进制值的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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