我有一个调用的函数replaceByte(x,n,c)是替换字节n在x与c具有以下限制:
replaceByte(0x12345678,1,0xab) = 0x1234ab78! ~ & ^ | + << >>Max ops:10
int replaceByte(int x, int n, int c) {
int shift = (c << (8 * n));
int mask = 0xff << shift;
return (mask & x) | shift;
}
Run Code Online (Sandbox Code Playgroud)但是当我测试它时,我得到了这个错误:
错误:测试replaceByte(-2147483648 [0x80000000],0 [0x0],0 [0x0])失败...... ...给出0 [0x0].应该是-2147483648 [0x80000000]
在意识到*不是合法的操作员后,我终于弄明白了......如果你好奇,这就是我所做的:
int replaceByte(int x, int n, int c) {
int mask = 0xff << (n << 3);
int shift = (c << (n << 3));
return (~mask & x) | shift;
}
Run Code Online (Sandbox Code Playgroud)
由于这看起来像家庭作业,我不会发布代码,但列出了您需要执行的步骤:
c成一个32位的号码,以便在换挡你不会失去任何位c向左n==0移动适当的位数(如果没有移位,如果n==1移位8等)x,然后将此掩码移动与最后一步相同的量x并将相应的位清零xc值的按位OR(或加法)并x替换后者的屏蔽位啊...你快到了。
只是改变
return (mask & x) | shift;
Run Code Online (Sandbox Code Playgroud)
至
return (~mask & x) | shift;
Run Code Online (Sandbox Code Playgroud)
本mask应包含除区域被掩盖,而不是相反所有的人。
我正在使用这个简单的代码,它在gcc中可以正常工作
#include<stdio.h>
int replaceByte(int x, int n, int c)
{
int shift = (c << (8 * n));
int mask = 0xff << shift;
return (~mask & x) | shift;
}
int main ()
{
printf("%X",replaceByte(0x80000000,0,0));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12232 次 |
| 最近记录: |