我尝试用C中的位操作打包和解包数据。 我的期望是如果输入4个输入为1,2,3,4,则输出应为1234。 但我没有按预期获得输出。请让我知道我的代码有什么问题,或者我的预期输出本身是错误的。
#include <stdio.h>
void displabits(int input)
{
int mask=0x1, i;
for (i=31; i>=0; i--)
{
mask = 1 << i;
putchar((input & mask)? '1' : '0');
if(i%8 == 0)
putchar(' ');
}
printf("\n");
}
int main()
{
int a, b, c, d, packed_output=0, mask=0x1, p=0, q=0, r=0, s=0, temp;
printf("Enter first character\r\n");
scanf("%d",&a);
displabits(a);
printf("Enter second character\r\n");
scanf("%d",&b);
displabits(b);
printf("Enter third character\r\n");
scanf("%d",&c);
displabits(c);
printf("Enter fourth character\r\n");
scanf("%d",&d);
displabits(d);
a = a << 24;
displabits(a);
b = b << 16;
displabits(b);
c = c << 8;
displabits(c);
/* Packing data start */
packed_output = packed_output | a;
packed_output = packed_output | b;
packed_output = packed_output | c;
packed_output = packed_output | d;
printf("packed_output = %d\r\n", packed_output);
printf("packed_output in 32 bit format formar");
displabits(packed_output);
/* Packing data end */
/* Unpacking data start */
mask = ~(~0<<8)<<(31-8+1);
p = packed_output & mask;
p = p >> 24;
mask = ~(~0<<8)<<(23-8+1);
q = packed_output & mask;
q = q >> 16;
mask = ~(~0<<8)<<(15-8+1);
r = packed_output & mask;
r = r >> 8;
mask = ~(~0<<8)<<(7-8+1);
s = packed_output & mask;
printf("unpacked output's are as follows\r\n");
printf("first character = %d\r\n", p);
printf("first character in bit format\r\n");
displabits(p);
printf("second character = %d\r\n", q);
printf("second character in bit format\r\n");
displabits(q);
printf("third character = %d\r\n", r);
printf("third character in bit format\r\n");
displabits(r);
printf("fourth character = %d\r\n", s);
printf("fourth character in bit format\r\n");
displabits(s);
/* Unpacking data end */
return 0;
}
我已将打包和解包逻辑放在相同的代码库中。
答案 0 :(得分:0)
主要问题是您在不同的基础上执行操作。这就是你得到意想不到的答案的原因。 n << p
是二进制算术,实际上等于n * (2 ^ p)
。但是,你想要的是n * (10 ^ r)
。所以,如果你想以人类可读的形式得到你的答案,你需要一个常规的十进制算术,如:
a = a * 1000;
b = b * 100;
c = c * 10;
packed_output += a;
packed_output += b;
packed_output += c;
packed_output += d;