1

I try to read binary(executeable) files, butsome problem as it prints extra character(0xffffff) after every few bytes. But this code work perfectly for text file(Non-binary). The code is:

int main(int argc, char **argv) { uint64_t i=0; FILE * fp=fopen(argv[1],"rb"); uint8_t a; long int size=0; char *msg; size=findSize(argv[1]); msg=(char *)malloc(size+1); while((a=fgetc(fp))!=EOF) { printf("%02x",a); msg[i]=(char)a; i++; if(i==size) break; } i=0; for(i=0;i<size;i++) { printf("%x",msg[i]); } return 0; } 

When i try to print the value(s) of a, It works perfectly, while printing msg[i], it prints extra bytes i,e:

Orginal bytes: 0xa31c4b1ab66b900

Output with extra bytes: 0xa31c4ffffffb1ffffffafffffffb66ffffffb900

5
  • 2
    fgetc() returns an int value. So, a should be defined as an int. Commented Aug 7, 2019 at 10:27
  • ... which is especially important when reading binary data, to distinguish EOF from 0xFF. Commented Aug 7, 2019 at 10:28
  • Default parameter promotion converts a char to an int when passing to printf. This include sign extensions for negative values. Commented Aug 7, 2019 at 10:30
  • and the fgetc thing is relevant when you're working with binary files Commented Aug 7, 2019 at 10:33
  • also long might not be sufficiently large to contain every file size, but it perhaps wouldn't be a problem. Commented Aug 7, 2019 at 10:34

1 Answer 1

2
char *msg; 

Your msg variable has datatype char, which is probably signed on your platform. That means, it represents values from -128 to +127.

printf("%x",msg[i]); 

Any arguments to printf() that have an integer datatype smaller than int will be expanded to int. That conversion will keep the arithmetic value, so -128 which is 0x80 in char, will expand to 0xFFFFFF80 for int.

To avoid this, you need to store or cast the values to unsigned char first. The uint8_t type is same as unsigned char and easier to read, so:

printf("%x", (uint8_t)msg[i]); 

That way the numeric value will range from 0 to 255, like you would expect, and print as 0x00 to 0xFF even after the implicit conversion to int.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.