位移导致负数

时间:2013-04-01 01:50:35

标签: c bit-shift

我正在处理一项处理压缩和解压缩的任务。更具体地说,是行程编码的变体(9位块)。我遇到的问题涉及“类型”位的符号。我能够获得所需的位,但是,在该位应为1的情况下,我的printf返回-1。这会让我相信我没有在我的位移中做正确的事情,但我不知道那可能是什么。

void bitShift(char * mostFreq, unsigned char * byteBuf, int byteCount) {
    char type;
    int typels = 0;
    int typers = 7;

    int i = 0;
    for(i = 0; i < byteCount - 1; i++) {
            type = byteBuf[i];
            printf("type before = %d\t", (unsigned int)type);
            type = type << typels;
            type = type >> typers;
            typels++;
            printf("type after = %d\n", (unsigned int)type);
    }/*End for i*/


    for(i = 0; i < byteCount; i++)
            byteBuf[i] = 0;

}/*End bitShift*/

void decompressFile(char * mostFreq) {
    unsigned char byteBuf[9] = { 0 };
    int num, byteCount, i;
    num = 0; byteCount = 0; i = 0;
    unsigned char buf;
    while((num = read(0,&buf, 1)) > 0) {
            byteBuf[byteCount] = buf;
            byteCount++;
            if(byteCount == 9) {/*Flush bytes if buffer is full*/
                    bitShift(mostFreq, byteBuf, byteCount);
                    for(i = 0; i < 9; i++) {
                            byteBuf[i] = 0;
                    }/*End for i*/
                    byteCount = 0;
            }/*End if*/
    }/*End while*/
    if(num == 0) {/*If EOF*/
            if(byteCount != 0) {/*Bits have not been flushed*/
                    bitShift(mostFreq, byteBuf, byteCount);
            }/*End if*/
    } else if(num < 0) {
            perror("Read error");
            exit(1);
    }/*End else if*/

}/*End decompressFile*/

1 个答案:

答案 0 :(得分:4)

您的问题是您将type声明为普通char,在您的系统中似乎是签名类型。

因此,当你有例如0x80时,它实际上是-128,一个负数,当它向右移动时,符号位被扩展:1位:0xC0 (-64) ,2位:0xE0 (-32),... 7位:0xFF (-1)

将其更改为unsigned char并完成!