gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:27 26 4
gpt4 key购买 nike

所以我们需要写一个方法

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com