位操作,主要是〜
Bit Operations, mainly ~
本文关键字:位操作 更新时间:2023-10-16
我当前正在将十进制转换为二进制,确保它是8位。除〜(非)操作外,所有位操作都起作用。它们是一个巨大的整数价值。我不确定为什么,因为其他位操作可行。这是我的代码:(评论的线是不起作用的)
编辑:如果我想获得8位二进制字符串,我该怎么办?使用未签名的字符?如果我将所有未签名的INT更改为未签名的字符,那么我的二进制函数会产生错误的二进制转换。
#include <iostream>
#include <string>
using namespace std;
string BinaryToDecimal(unsigned int dec)
{
string binary = "";
float remainder = 0.0f;
while( dec != 0 )
{
remainder = dec % 2;
dec /= 2;
if( remainder == 0 )
binary.append("0");
else
binary.append("1");
}
// Reverse binary string
string ret = string(binary.rbegin(), binary.rend());
return ret;
}
int main()
{
unsigned int a = 0;
unsigned int b = 0;
cout << "Enter a number to convert to binary: ";
cin >> a;
cout << "Enter a number to convert to binary: ";
cin >> b;
cout << "A = " << BinaryToDecimal(a) << endl;
cout << "B = " << BinaryToDecimal(b) << endl;
unsigned int c = a & b;
unsigned int d = a | b;
//unsigned int e = ~a;
//unsigned int f = ~b;
unsigned int g = a ^ b;
unsigned int h = a << 2;
unsigned int i = b >> 3;
cout << "A & B = " << BinaryToDecimal(c) << endl;
cout << "A | B = " << BinaryToDecimal(d) << endl;
//cout << "~A = " << BinaryToDecimal(e) << endl;
//cout << "~B = " << BinaryToDecimal(f) << endl;
cout << "A ^ B = " << BinaryToDecimal(g) << endl;
cout << "A << 2 = " << BinaryToDecimal(h) << endl;
cout << "B >> 3 = " << BinaryToDecimal(i) << endl;
}
如果您执行的二进制不在小的无签名整数上,则将获得大数字,因为大多数最重要的位将设置为1(倒数他们在操作数中的内容)。
在这种情况下,您正在进行~ 0
,这肯定会给您一个大量的数字,实际上是最大的未签名INT,因为所有位都将设置为1。
(您期望什么结果?)
您正在使用unsigned int
进行操作,因此,由于从MSB开始的领先1,因此少量的反转变成了大数字。如果您只希望表示形式为8位,则应将unsigned char
用于其存储。
但是您不能将A或B更改为unsigned char
。否则,cin >> a
将将该号码的ASCII代码放在a
,而不是数字。例如,您的输入为5,它是0x35('5'),而不是数字5。
如果您不想更改代码的unsigned int
,则可以进行一些较小的增强
string BinaryToDecimal(unsigned int dec)
{
string binary = "";
float remainder = 0.0f;
dec &= 0xff; // only 8 bits you care about
while( dec != 0 )
{
....
,但是您正在使用 while( dec !=0 )
,这是有货物的。如果结果已经为0,则该功能将返回一个空字符串,而不是" 0000"。相反,您应该使用计数器仅计数8位。
for (int i = 0; i < 8; i++ ) {
if ((dec & 1) != 0)
binary.append("1");
else
binary.append("0");
dec >>= 1;
}
另外,使用位智能AND
测试位是0或1,而移动操作比/和%运算符更好。
最后,对于8位5(0000_0101),其反转为250(1111_1010),而不是1010。
相关文章:
- 对字符串进行位操作
- 对字符数组中的元素执行逐位操作
- 逐位操作的隐式类型转换
- 如何进行特定的位操作?
- C++避免位操作完全移位
- 使用双包装器类进行位操作(C++、clang)修复性能下降问题
- 使用位操作优化检查
- 子集相关位操作
- 使用 c++ 提升库的按位操作
- 位操作和异或
- 位操作将最左侧的设置位转换为右侧交替位?
- 为什么对小于 4 个字节的整数类型的位操作会发生意外行为?
- POD 类型的原子按位操作
- 如何使用位操作在单个整数中编码和解码两个数字
- __int128的位操作
- 使用位操作会影响内存消耗?
- 在具有位操作的函数中获得值
- C/C 位操作不会导致预期输出
- 在数组大小中使用位操作的原因
- 了解C++位操作中的二进制转换实现