开发者

fprintf won't write hexadecimal numbers that end in zero to a file correctly

开发者 https://www.devze.com 2023-03-22 14:40 出处:网络
I am able to write the correct hexadecimal values to my output file whenever the initial value 开发者_如何学JAVAof \'tag\' is odd. But I want to write my output in hex for both even and odd intitial \

I am able to write the correct hexadecimal values to my output file whenever the initial value 开发者_如何学JAVAof 'tag' is odd. But I want to write my output in hex for both even and odd intitial 'tag' values. If the initial value of 'tag' is even and above the number 20 and I try to write a hexadecimal number to the output file I just get the characters ちㄠ instead of A0 1. However, if I change it to write in decimal format I get the correct values. If I only write fieldnumber[0] to the file instead of both fieldnumber[0] and 'secondaryvalue' then I get the correct output value in hexadecimal. Also if I change fieldnumber[0] only to write as decimal output and leave 'secondaryvalue' to write as hex it will give me the write values. My code is as follows (with unrelated lines omitted:

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[] is a long long value (8 bytes) which needs to be printed with the format %llx rather than %x as you are doing it (check you man page), you may require a different output formatting such as %lx or %Lx depending on which compiler and clib your are using.

0

精彩评论

暂无评论...
验证码 换一张
取 消