c# - 编写方法 ByteSwap 但未按计划工作

标签 c# c++ c

所以我们需要写一个方法

byteSwap - 交换第 n 个字节和第 m 个字节

  • 示例:byteSwap(0x12345678, 1, 3) = 0x56341278
  • byteSwap(0xDEADBEEF, 0, 2) = 0xDEEFBEAD
  • 你可以假设 0 <= n <= 3, 0 <= m <= 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;

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

最佳答案

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

关于c# - 编写方法 ByteSwap 但未按计划工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9122804/

相关文章:

c++ - double 的高性能加法和乘法的常量形式

c++ - Header实现变量重定义不显示错误

c - fork()返回0,但是子进程getpid()!=0。为什么?

c - 将字符数组视为整数 - Learn C the Hard Way 额外学分

c++ - C/C++函数/方法修饰

c# - 使用 RestSharp 返回一个简单的 Guid

c# - 如何向 Visual Studio C++ ATL 项目创建的 COM .dll 添加新函数

c++ - 使用 'new'创建实例后出现堆栈溢出错误

c# - 将方法定义为静态方法更好吗?

c# - Dump() 对象到 JSON pretty-print 字符串