Printf () prints a character as 32 bits

I run a quick test to make sure I have pointer arithmetic:

main.c

#include <stdio.h> #include <stdlib.h> #define ADDRESS 0xC0DCA11501LL #define LENGTH 5 void print_address( char *, char ); /* Main program */ int main( int argc, char *argv[] ) { char nums[ LENGTH ]; /* LSB first */ for( int i = 0; i < LENGTH; i++ ) { nums[ i ] = ( ADDRESS >> ( 8 * i ) ) & 0xFF; } print_address( nums, LENGTH ); system("PAUSE"); return 0; } void print_address( char *data, char len ) { char *data_ptr = data; while( len-- ) { printf( "%X\n", *data_ptr++ ); } } 

I expect ADDRESS bytes to be printed in LSB format in hexadecimal format. But the last 3 bytes seem to be printed with 32-bit length:

 1 15 FFFFFFA1 FFFFFFDC FFFFFFC0 Press any key to continue . . . 

Is this because of my bitrate arithmetic, something compiler specific, some printf() behavior?

(I am using MinGW GCC v6.3.0 for Windows 10 to compile.)

+5
source share
3 answers

I believe that your char used as a signed value and that you see FFFF , because 0xA1 greater than 0x80 , and therefore appears signed. Try using an unsigned char pointer (for both the nums and data array in the function prototype) and the problem should go away.

+5
source

The char type seems to be signed in your environment, so A1 as an 8-bit value actually represents a negative number. Note that varargs of printf promoted to int, and a negative number is filled with leading 1 bits. In other words, a signed A1 when moving up to a 32-bit integer will give FFFFFFA1 . That's why.

Use unsigned char instead:

 void print_address( unsigned char *, char ); /* Main program */ int main( int argc, char *argv[] ) { unsigned char nums[ LENGTH ]; /* LSB first */ for( int i = 0; i < LENGTH; i++ ) { nums[ i ] = ( ADDRESS >> ( 8 * i ) ) & 0xFF; } print_address( nums, LENGTH ); system("PAUSE"); return 0; } void print_address( unsigned char *data, char len ) { unsigned char *data_ptr = data; while( len-- ) { printf( "%X\n", *data_ptr++ ); } } 
+2
source

The problem is that printf does not know what the data type is char.

try it

 void print_address( char *data, char len ) { char *data_ptr = data; while( len-- ) { printf( "%02X\n", *data_ptr++ &0xFF); } } 

Result:

 [ jmgomez@d1 tmp]$ ao 01 15 A1 DC C0 sh: PAUSE: command not found [ jmgomez@d1 tmp]$ 
0
source

Source: https://habr.com/ru/post/1275924/


All Articles