JPEG 디코더를 구현 중이고 한 단계에서 주어진 비트 수인 (positive if 1th bit = 1)
에서 값의 부호를 결정해야합니다. 1 번째 비트가 0
일 때이 값에서 2의 보수를 얻어야하고 결과에 1을 더 추가해야합니다.비트 조작
I했습니다이 일을 할 수있는 다음과 같은 기능을 가지고 :
#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;
}
고마워요!
는 0을 후행 추가합니다. –
당신은 이것을 읽을 수 있습니다 : http://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true – martinkunev
더 적은에 0을 더합니다 마스크의 유효 비트는 2의 보수로, -1은 패턴 '1111111 ... 111'입니다. 따라서 -1 << 3은 11111 ... 111000입니다. –