按位切换最重要和最不重要的字节

时间:2013-07-16 11:23:08

标签: c++ c bit-manipulation

假设我有一个存储2个字节的缓冲区:

char *buf=new char[4];
// 00000010 00000000 (.. other stuff ..)

我想要做的是用最重要的字节切换最少的字节,并将该值存储在变量中。试着这样做:

short len=buf[1];
len <<= 8;
len |= buf[0];
    // Result, as expected: 00000000 00000010

它可以处理罚款,除非最重要的字节(buf [0])是&gt; = 128,这使得或运算符(|)用1填充短的一半。例如:

Original: 10000110 00000000
Should be: 00000000 10000110
But is: 11111111 10000110

谢谢(哦,我正在用file.read(...,4)读取文件中的字节; - 如果这是相关的话,甚至不知道了)

3 个答案:

答案 0 :(得分:6)

您的实施显然使用已签名号码的two's complement表示。改为使用无符号值

unsigned char * buf = new unsigned char[2];
...

unsigned short len=buf[1];
len <<= 8;
len |= buf[0];

答案 1 :(得分:0)

试试这个:

unsigned short buf;
...
buf = buf << 8 | buf >> 8;

或者只是执行排列:

char buf[2];
char tmp;
...
tmp = buf[0];
buf[0] = buf[1];
buf[1] = tmp;

我希望这有帮助!

答案 2 :(得分:0)

 buff = 11001010 01011100;
 //copy this buff, I am writing it directly below  

 copy_of_buff = 11001010 01011100;  
 buff_hi = (buff >> 8);  //Hence after this exec, buff_hi = 00000000 11001010  
 buff_lo = (copy_of_buff << 8); //Hence after this exec, buff_lo = 01011100 00000000

 out_buff = (buff_hi)||(buff_lo); //Hence after this exec, out_buff = 01011100 11001010