2012-02-03 51 views
0

所以我们需要编写一个方法编写方法BYTESWAP但按计划

BYTESWAP不工作 - 交换的第n个字节和第m个字节

  • 实例:BYTESWAP(0×12345678,1,3)= 0x56341278
  • BYTESWAP(0xDEADBEEF,0,2)= 0xDEEFBEAD
  • 你可以假设0 < = N < = 3,0 < =米< = 3
  • 法律运作:! 〜&^| + < < >>

也不能使用循环/递归

但我下面的代码失败,此测试案例:

测试BYTESWAP(-2147483648 [0x80000000的],0为0x0] 3 [0x3])失败... ...给出-128 [0xffffff80]。应该是128 0x80的]

不知道为什么,虽然这是到目前为止我的代码

int byteSwap(int x, int n, int m) { 
int nBitShift = n << 3; 
int mBitShift = m << 3; 
int nByte = x & (0xFF << nBitShift); //gets the byte at position n 
int mByte = x & (0XFF << mBitShift); //gets the byte at position m 
int newX = x + ~(nByte + mByte) + 1; //make 0's in the nth and mth byte 
nByte = nByte >> nBitShift; //shift back  
nByte = nByte << mBitShift; //shift to the mth spot 
mByte = mByte >> mBitShift; //shift back 
mByte = mByte << nBitShift; //shift to the nth spot 

return nByte + mByte + newX; 

}

编辑:是的,这是硬件,但我需要帮助

+0

这是一个家庭作业吗? – 2012-02-03 02:09:02

+0

“我们”,所以这当然是一项功课。 :D – 2012-02-03 02:10:20

+0

你正在写什么语言?这是功课吗?为什么你给“newX”加1? – Joe 2012-02-03 02:13:47

回答

3

的算术移位一个有符号值的符号 - 扩展操作数。如果您将临时变量的类型切换为unsigned,则您的解决方案可以避免此问题。

+0

这工作非常感谢你。但我没有完全理解你的意思是“扩展”操作数 – user1186549 2012-02-03 02:43:53

+1

@ user1186549 [This atricle](http://en.wikipedia.org/wiki/Sign_extension)解释了符号扩展。 [这篇其他文章](http://en.wikipedia.org/wiki/Arithmetic_shift)有一张不错的图片,显示当数字右移时MSB会发生什么。 – dasblinkenlight 2012-02-03 02:53:58

+0

有没有办法使用无符号?如果我使用无符号数,则赋值不会赋予点数....当有负数时,我总是被赋值为1 – user1186549 2012-02-03 03:05:05

1

这将如何工作?

int byteswap(int x,int n,int m) 
{ 
    unsigned char *x_bytes = (unsigned char*)&x, tmp = x_bytes[n]; 
    x_bytes[n] = x_bytes[m]; 
    x_bytes[m] = tmp; 
    return x; 
} 

我知道这可能不是你的讲师/某人的想法,但它只是为了表达一个想法。如果有的话,它不使用循环或递归。 ;)

+0

不是依赖于CPU的字节顺序的方法。通过以上定义,字节0是最不重要的字节,并且此方法不适用于首先存储MSB的CPU。 – 2012-02-03 02:31:48

+0

你当然是对的。 – 2012-02-03 02:34:16

0

这是一个“发烧友”的解决方案。

unsigned int byteswap(const unsigned int x, unsigned int n, unsigned int m) { 
    unsigned int mask; 
    m <<= 3; 
    n <<= 3; 
    mask = ((x >> m)^(x >> n)) & 0xFFU; 
    mask = (mask << m) | (mask << n); 
    return (x^mask); 
} 
+0

我认为这也适用于普通的'int's。 – 2012-02-05 00:28:48