所以我们需要编写一个方法编写方法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;
}
编辑:是的,这是硬件,但我需要帮助
这是一个家庭作业吗? – 2012-02-03 02:09:02
“我们”,所以这当然是一项功课。 :D – 2012-02-03 02:10:20
你正在写什么语言?这是功课吗?为什么你给“newX”加1? – Joe 2012-02-03 02:13:47