我想显示从输入接收的整数的四个字节中的每个字节的二进制值。我尝试用位操作符来做这个但是它运行得不好。谁能告诉我怎么能这样做?
代码如下所示:
void main()
{
int x;
int n;
printf("Please introduce an integer number");
scanf("%d",&x);
for (n=0; n<=3; n++) {
printf("byte %d of 0x%X is 0x%X\n",n,x,getByte(x,n));
}
}
int getByte(int x, int n)
{
return (x >> (n << 3)) & 1;
}
但它返回:字节0为1 字节1为0 字节2为0 字节3为0,而不是当我插入8时。
答案 0 :(得分:2)
不使用位运算符的解决方案......
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
string digits[2] = {"0","1"};
// return an integer in binary format
string num2bin(int n){ return n<2 ? digits[n] : num2bin(n/2) + digits[n%2]; }
// get the b-th byte of an integer
int getByte(long n, int b){ return (long)(n/pow(256,b)) % 256; }
int main() {
long n = 987654321; // or whatever
// loop through the bytes in order
for (int b=0;b<4;b++) {
cout << "byte " << b << " = " << num2bin(getByte(n,b)) << endl;
}
}
输出:
byte 0 = 10110001
byte 1 = 1101000
byte 2 = 11011110
byte 3 = 111010
答案 1 :(得分:1)
#include <bitset>
#include <iostream>
int i;
std::cin>>i;
std::cout<<std::bitset<8*sizeof(int)>(i);
答案 2 :(得分:0)
int x = ...;
int b0 = x&255;
int b1 = (x >> 8)&255;
int b2 = (x >> 16)&255;
int b3 = (x >> 24)&255;