Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print out the second byte in printf() in one single line

How can i print out the second byte in a stored integer in one line on printf as shown in
in the second printf()

unsigned int aNum = 258; // 4 bytes in allocated memory
unsigned char * newP = &aNum;

printf("\n with a pre-created pointer %02i",newP[1]); //getting the second byte[02]
printf("\n address without a pre-created pointer %02i",(unsigned char)aNum); // getting the first byte[01]
 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think it would be better to use bitwise operators:

unsigned num = ...
unsigned char lowest_byte = num & 0xFF;
unsigned char second_low_byte = ((num & 0xFF00) >> 8);
printf ("\nfirst byte: %02i, second byte: %02i\n", (unsigned) lowest_byte, (unsigned)second_low_byte);

You don’t really need temporary variables of course, you can do the bitwise operations directly in printf operands.


If you absolutely need to use an array, then this is the way:

unsigned char *ptr = (unsigned char*)#
printf ("\nfirst byte: %02x, second byte: %02x\n", ptr[0], ptr[1]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading