【发布时间】:2016-09-02 09:30:19
【问题描述】:
我正在实现一个 JPEG 解码器,在一个步骤中,我需要根据给定位数 (positive if 1th bit = 1) 确定一个值的符号。
当第 1 位为 0 时,我必须从该值中获取二进制补码,并将结果加 1。
我有以下功能来完成这项工作:
#include <stdio.h> /* printf */
#include <string.h> /* strcat */
#include <stdlib.h> /* strtol */
typedef int bool;
#define true 1
#define false 0
int DetermineSign(int val, int nBits)
{
bool negative = val < (1<<(nBits-1));
if (negative)
{
// (-1 << (s)), makes the last bit a 1, so we have 1000,0000 for example for 8 bits
val = val + (-1 << (nBits)) + 1;
}
// Else its unsigned, just return
return val;
}
谁能解释一下(-1 << (nBits))这个表达式有什么作用以及它是如何工作的?
我知道作者有一个评论来解释它,但我也用下面的函数对其进行了测试,它返回了另一个结果。
const char *byte_to_binary(int x)
{
static char b[9];
b[0] = '\0';
int z;
for (z = 128; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}
return b;
}
int main(void)
{
char testValue = 0;
testValue = (-1 <<(testValue));
printf("%s\n", byte_to_binary(testValue)); // output 1111 1111 doesn't it has to be 1000 000?
return 0;
}
谢谢!
【问题讨论】:
-
添加尾随零。
-
您可能想阅读以下内容:stackoverflow.com/questions/809227/…
-
它将低意义位中的零添加到掩码中(在二进制补码中,-1 是模式
1111111...111。所以-1 << 3是11111...111000。
标签: c bit-manipulation jpeg