Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print 1 byte with printf?

I know that when using %x with printf() we are printing 4 bytes (an int in hexadecimal) from the stack. But I would like to print only 1 byte. Is there a way to do this ?

like image 397
ahg8tOPk78 Avatar asked Jan 13 '17 15:01

ahg8tOPk78


People also ask

What is %U in printf?

Unsigned Integer Format Specifier %u The %u format specifier is implemented for fetching values from the address of a variable having an unsigned decimal integer stored in the memory. It is used within the printf() function for printing the unsigned integer variable.

What is %A in printf?

The %a formatting specifier is new in C99. It prints the floating-point number in hexadecimal form. This is not something you would use to present numbers to users, but it's very handy for under-the-hood/technical use cases.

Can we use %d in printf?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

What is %B in printf?

The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).


1 Answers

Assumption:You want to print the value of a variable of 1 byte width, i.e., char.

In case you have a char variable say, char x = 0; and want to print the value, use %hhx format specifier with printf().

Something like

 printf("%hhx", x);

Otherwise, due to default argument promotion, a statement like

  printf("%x", x);

would also be correct, as printf() will not read the sizeof(unsigned int) from stack, the value of x will be read based on it's type and the it will be promoted to the required type, anyway.

like image 100
Sourav Ghosh Avatar answered Oct 14 '22 06:10

Sourav Ghosh