gpt4 book ai didi

c - 位移位结果为负数

转载 作者:行者123 更新时间:2023-11-30 18:32:13 25 4
gpt4 key购买 nike

我正在做一项涉及压缩和解压缩的作业。更具体地说,是游程长度编码的变体(9 位 block )。我遇到的问题涉及“类型”位的符号。我能够获取所需的位,但是,在该位应该为 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*/

最佳答案

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

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

将其更改为unsigned char并完成!

关于c - 位移位结果为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com