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

Time:01-16

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 i",newP[1]); //getting the second byte[02]
printf("\n address without a pre-created pointer i",(unsigned char)aNum); // getting the first byte[01]
 

CodePudding user response:

Consider this solution:

#include <stdio.h>

int main(void) {
    unsigned int aNum = 0x1a2b3c4du; // 4 bytes in allocated memory

    for (int i = 0; i < 4;   i) {
        printf("\nbyte %d  x", i, (unsigned int) ((unsigned char *) &aNum)[i]);
    }
}

CodePudding user response:

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: i, second byte: i\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*)&num;
printf ("\nfirst byte: x, second byte: x\n", ptr[0], ptr[1]);
  •  Tags:  
  • Related