Is there a format specifier for sprintf in C that maps a char to hex in the same way that %x maps an int to hex?
Is there a format specifier for sprintf in C that maps a char to
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes and no.
Since
sprintftakes a variable argument list, all arguments undergo default promotion beforesprintfreceives them. That meanssprintfwill never receive achar— acharwill always be promoted tointbeforesprintfreceives it (and ashortwill as well).Yes, since what
sprintfis receiving will be anint, you can use%xto convert it to hex format, and it’ll work the same whether that value started as achar,short, orint. If (as is often the case) you want to print 2 characters for each input, you can use%2.2x.Beware one point though: if your
charis signed, and you start with a negative value, the promotion tointwill produce the same numerical value, which normally won’t be the same bit pattern as the original char, so (for example) a char with the value-1will normally print out asffffifintis 16 bits,ffffffffif int is 32 bits, orffffffffffffffffifintis 64 bits (assuming the typical 2’s complement representation for signed integers).