• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 530
  • Last Modified:

printing hex values for chars

I need to send a packet that contains the following 3 bytes to another program.

The bytes are the hex value 0x202

I wanted to store the value in an integer and then copy the first 3 bytes of the integer
into a buffer for transmission.

However when I print out the buffer contents I get the hex values 220 and not 202

I also tried using a constant char buffer set to 0x202 and this works, but I'm a little bit
confused why the integer method didn't work and I would like to figure this out.

The output for the function attached is

ID == 514  D(hex) == 202
BYTE[0]  == 2 // why does this print 220 and not 202?
BYTE[1]  == 2
BYTE[2]  == 0

CONST_CHAR[0]  == 2
CONST_CHAR[1]  == 0
CONST_CHAR[2]  == 2

void printHex()
	const unsigned char CONST_CHAR[] = "\x2\x0\x2";
	const unsigned int ID = 0x202;
	unsigned char buf[3];


	printf("ID == %d  D(hex) == %x \n",ID,ID);
	for(int i =0; i < sizeof(buf);i++){
		printf("BYTE[%d]  == %x \n",i,buf[i]);

	for(int i =0; i < sizeof(CONST_CHAR)-1;i++){

		printf("CONST_CHAR[%d]  == %x \n",i,CONST_CHAR[i]);


Open in new window

  • 2
1 Solution
0x202 is only two bytes : the byte 0x02 and the byte 0x02.

So, use :

>> const unsigned char CONST_CHAR[] = "\x02\x02";

and send both bytes.
It's better to initialize the array like this though :

        const unsigned char CONST_CHAR[] = { 0x02, 0x02 };

just to avoid problems with null bytes being interpreted as the end of a string, and to make it explicit that you're dealing with unsigned char values, and not with char's.
dev110Author Commented:
I knew it would be something simple.
I should have done
const unsigned int ID = 0x00020002;


const unsigned int ID = 0x202;

Thanks for both of your comments
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now