• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 522
  • 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];
	memcpy(buf,&ID,sizeof(ID)-1);

	printf("\n\n");

	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]);

	}
	printf("\n\n");
	for(int i =0; i < sizeof(CONST_CHAR)-1;i++){

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

}

Open in new window

0
dev110
Asked:
dev110
  • 2
1 Solution
 
Infinity08Commented:
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.
0
 
Infinity08Commented:
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.
0
 
dev110Author Commented:
I knew it would be something simple.
I should have done
const unsigned int ID = 0x00020002;

not

const unsigned int ID = 0x202;

Thanks for both of your comments
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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