S Andrew
S Andrew

Reputation: 7198

Not able to print hex bytes in C

I know this question has already been asked many times. I am facing a problem where I am getting few hex bytes via serial communication in ubuntu. I have written a C code which reads all the data and display it. It is working fine as I have tested it with many strings. I also have another system running windows and a software named Docklight. This software is giving me hex bytes and I need to receive it in my application. Hex bytes are like below:

FF AA 2E 0F CC 0D

I have connected both the systems via null modem cable. Now to print hex bytes, we need to include %02X in printf statement. Doing this, it gave me a warning of format ‘%X’ expects argument of type ‘unsigned int’, but argument 2 has type ‘unsigned char *’. I searched about this and replaced it with %p. Here is the code:

unsigned char buf[255];

res = read(fd,buf,255);
buf[res]='\0';

printf("data: %p\n",buf);

The output of the printf statement is data: 0x603380. I opened the buf variable to see the exact values which are below:

Name : buf
Details:"ÿª.\017Ì\n", '\0' <repeats 248 times>
Default:0x603380 <buf>
Decimal:6304640
Hex:0x603380
Binary:11000000011001110000000
Octal:030031600

Now I really don't know why it shows random characters like ÿª.\017Ì\n The output of the printf is may be because it has combined all the bytes into one and displayed its hex equivalent.

I actually need to save each byte like FF and AA in an array. But just for the time being, I thought of first displaying it. What could be the issue. Why it is not displaying hex bytes. Can anyone give me suggestions on this. I also need to know that when we transmit hex bytes via serial, how does the receiving end should receive it. It should be saved as int or strings. Thanks.!

Upvotes: 0

Views: 1918

Answers (2)

gabry
gabry

Reputation: 1422

This is a basic C problem, you are giving printf() a pointer and expecting it to show your hex dump, as if it was a string. That's not the way it works.

You should do something like this:

unsigned char buf[255];

res = read(fd,buf,255);
// AN HEX BUFFER IS NOT A STRING DO NOT TERMINATE IT
// buf[res]='\0';

printf("data: ");
for (int i = 0; i < res; ++i)
  printf("%02x ", (int)buf[i]);

printf("\n");

The option %p of printf it's used to dump the pointer ADDRESS, not the contents a pointer point to.

Upvotes: 5

Pras
Pras

Reputation: 4044

printf("data: %p\n",buf);

This is printing address of variable buf, as you have used %p To display buf in hex, you need to print it in loop character by character

printf("data: %.2X\n",buf[i]);// i from 0 to res

"I actually need to save each byte like FF and AA in an array." Its already in your array ie buf, you need to print it correctly, if you want to display in hex

Upvotes: 3

Related Questions