c - 在 C 中对数字进行符号扩展

标签 c

我在尝试通过提取部分位串来对数字进行符号扩展时遇到问题。当它是一个负数时会有麻烦,它会将数字环绕到正数。 这是我的代码:

//  printf("add1 \n");
unsigned short r1 = (instruction>>6)&7;
signed short amount = (instruction& 31);   //right here! i am trying to get the last 5 bits and store it in a register but i can't figure out how to make it negative if it is negative
//  printf("\namount is %d \n", amount);
unsigned short dest = (instruction>>9)&7;
state->regs[dest] = state->regs[r1]+amount;
setCC(state,state->regs[r1]+amount);

最佳答案

对于位模式,使用十六进制常量通常比使用十进制更容易。

signed short amount = (instruction & 0x1F);

然后要对数字进行符号扩展,请检查符号位(假设此处的符号位是提取的 5 个位中最左边的位)。 如果已设置,则进行二进制反转并加 1。 取 5 位值的 2 的补码(反转并加一),然后取全角结果的 2 的补码(反转并加 1)。

if (amount & 0x10)
    amount = ~(amount^0x1F + 1) + 1;

例如。

             5-bit "bitfield"
             X XXXX
0000 0000 0001 1111
0000 0000 0000 0000 invert x ^ 0x1F (= 1 1111)
0000 0000 0000 0001 add 1
1111 1111 1111 1110 invert ~
1111 1111 1111 1111 add 1

0000 0000 0001 0000
0000 0000 0000 1111 invert x ^ 0x1F (= 1 1111)
0000 0000 0001 0000 add 1
1111 1111 1110 1111 invert ~
1111 1111 1111 0000 add 1

糟糕。更简单:

-(x^0x1F + 1)  Assuming the machine operates with 2's-complement

0000 0000 0001 0110
0000 0000 0000 1001 invert
0000 0000 0000 1010 add 1 (yielding the full-width absolute value)
1111 1111 1111 0110 negate

关于c - 在 C 中对数字进行符号扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16220983/

相关文章:

c - 如何将 dlsym 返回的指针正确赋值给函数指针类型的变量?

在c语句中计算标记

c++ - nm、objdump 和 pfunct 给出相互矛盾的答案来检查函数是否内联

c - 幂为-3/2或-5/2的c语言pow函数的实现

c++ - 在没有 cin 的情况下从控制台获取输入?

c - 使用 "->"而不是 "."访问结构会出现段错误

c - FFT 重新排序阶段

c - Murmurhash2 Unsigned Int 溢出

c - c 中的静态内联函数

c++ - assembly 打印 float