gpt4 book ai didi

c - fprintf 不会将以零结尾的十六进制数正确写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:38 26 4
gpt4 key购买 nike

只要“标签”的初始值为奇数,我就能够将正确的十六进制值写入输出文件。但我想以十六进制形式为偶数和奇数初始“标签”值编写输出。如果'tag'的初始值是偶数且大于数字 20,并且我尝试将十六进制数写入输出文件,我只会得到字符 ちㄠ 而不是 A0 1。但是,如果我将其更改为以十进制格式写入我得到正确的值。如果我只将 fieldnumber[0] 写入文件而不是将 fieldnumber[0] 和 'secondaryvalue' 写入文件,那么我将得到正确的十六进制输出值。此外,如果我将 fieldnumber[0] 更改为仅写入十进制输出并将“secondaryvalue”保留为十六进制,它将给我写入值。我的代码如下(省略无关行:

int uint32_pack (uint8_t *fieldnumber, uint32_t value, uint8_t *out);

int main(){

uint32_t initvalue = 2;
int return_rv;
uint8_t *tag = (uint8_t *) malloc(sizeof(uint8_t));

uint8_t *tempout= (uint8_t *) malloc(sizeof(uint32_t));
*tag = 20; //even number that when processed won't write the correct value

return_rv = uint32_pack (tag, initvalue, tempout);

free(tempout);

}

/* === pack() === */
/* Pack an unsigned 32-bit integer in base-128 encoding, and return the number
of bytes needed: this will be 5 or less. */

int uint32_pack (uint8_t *fieldnumber, uint32_t value, uint8_t *out)
{
unsigned rv = 0;
FILE *outfile;
FILE *wiretypetag;
int secondaryvalue;
outfile = fopen("hexdata.txt","w");
wiretypetag = fopen("wiretype.txt","w");


//encodes wire type and the field number
if (*fieldnumber <16){
*fieldnumber <<= 3;
fprintf(wiretypetag,"%x",*fieldnumber);
}
if (*fieldnumber < 32){
*fieldnumber <<= 3;
secondaryvalue = 0x01;
fprintf(wiretypetag,"%x %x",fieldnumber[0],secondaryvalue);
}
if (*fieldnumber < 48){
*fieldnumber += 0x10;
*fieldnumber &= 0x1F;
*fieldnumber <<= 3;
secondaryvalue = 0x02;
fprintf(wiretypetag,"%x %x",fieldnumber[0], secondaryvalue);
}

/* assert: value<128 */
out[rv++] = value;

fclose(outfile);
fclose(wiretypetag);

return rv;
}

最佳答案

filednumber[] 是一个 long long 值(8 字节),需要以 %llx 格式打印,而不是 %x在执行此操作时(查看手册页),您可能需要不同的输出格式,例如 %lx%Lx,具体取决于您使用的编译器和 clib。

关于c - fprintf 不会将以零结尾的十六进制数正确写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780690/

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