The reason why this is happening is that chars on your system are signed. When you pass them to functions with variable number of arguments, such as printf (outside of fixed-argument portion of the signature) chars get converted to int, and they get sign-extended in the process.

To fix this, cast the value to unsigned char:

printf("\\%02hhx", (unsigned char) pt->GUID[i]);

Demo.

Answer from Sergey Kalinichenko on Stack Overflow
Discussions

print hex value of char
You can do this another way: printf("%hhx\n", c); but older C does not have this length modifier so your first method is the most portable. Also, of you declared array to have type unsigned char, the cast would not be needed. Note that you are deliberately asking for the "wrong" answer -- the hexadecimal ... More on thecodingforums.com
🌐 thecodingforums.com
22
July 9, 2010
dash - How to printf ascii characters with hex or dec inside /bin/sh -c '...'? - Unix & Linux Stack Exchange
Nice.printf "\044\n" works well. ... Note that $ is only octal 44, hex 24 when expressed in the ASCII charset (and all its supersets such as iso8859-15, gb18030 or UTF-8). printf '\44\n' will print a $ on a large majority of POSIX systems, but certainly not all of them, and POSIX for example ... More on unix.stackexchange.com
🌐 unix.stackexchange.com
June 8, 2021
[C++] printf inserts f's when trying to print (special) char's as a hex number
Keep in mind that the C++ standard doesn't really specify any character encoding for such character literals or the "normal" string literals. This is all implementation-defined. Some compilers let you specify the (1) source character encoding and (2) the execution character encoding. I'm assuming your text editor stored your source code as ISO 8859-1 or 8859-15 and the compiler just takes the source code bytes "as is". This could be a portability problem. More on reddit.com
🌐 r/learnprogramming
3
5
March 29, 2019
Print character array as hex in C - Stack Overflow
9 then it would print 09.. not really required for the alpha characters as these are all in the two byte hexadecimal range 2015-09-20T05:31:15.407Z+00:00 More on stackoverflow.com
🌐 stackoverflow.com
🌐
Cplusplus
cplusplus.com › forum › beginner › 195511
printf characters as hex in C - C++ Forum
August 6, 2016 - I want to count the character frequency in a string and print them as hexadecimal.How can this be done with following code? ... What I want to do is following: Charatcters like alphabet,numbers etc. with printf above and just the escape sequences (\t , \n etc) as hex.I want to create a char with all escape characters and check it with frequency[index].If escape sequence printf hex,if not "normal" printf like above.But it doesn't work.Could someone help me out?
🌐
The Coding Forums
thecodingforums.com › archive › archive › c programming
print hex value of char | C Programming | Coding Forums
July 9, 2010 - You can do this another way: printf("%hhx\n", c); but older C does not have this length modifier so your first method is the most portable. Also, of you declared array to have type unsigned char, the cast would not be needed.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 65881-printing-hex-value-char.html
Printing Hex Value of a char
# include <stdio.h> int main () { char Name[9]={0x0}; char *p=NULL; printf("Enter an 8 letter name:\n\n"); fgets(Name, sizeof(Name),stdin); printf("name entered: %s\n\n", Name); printf("name entered in Hex:"); for(p=Name;*p && *p>' ';p++) { printf("x",*p); } printf("\n"); return 0; }
🌐
Reddit
reddit.com › r/learnprogramming › [c++] printf inserts f's when trying to print (special) char's as a hex number
r/learnprogramming on Reddit: [C++] printf inserts f's when trying to print (special) char's as a hex number
March 29, 2019 -
int main(int argc, char* args[]) {
    printf("%02x\n", (int) 'ê' );
    return 0;
}

This could should, to my understanding, print:

ea

instead it prints:

ffffffea

For "normal" char's it works as expected though, e.g.

printf("%02x\n", (int) 'j' );

prints

6a

This is consistenly the case for not-normally-used-in-english characters such as ê, Ù, Ü, or Ö, and the code works as expected for "normal" characters such as j, n, ?, or k.

I'm using Eclipse CDT with MinGW.

Anyone knows why this is the case, and possibly how to fix it? Thanks in advance.

EDIT: Figured it out, apparently the problem was with the char's being signed and these special characters having too high of a value, thus overflowing. To get the correct result you have to convert them to unsigned chars first, e.g.

printf("%02x\n", (int) (unsigned char) 'ê' );

Find elsewhere
🌐
Simply i
shieldadvanced.com › home › printing a string of hex characters to the screen
Printing a string of Hex characters to the screen - Simply i
August 9, 2007 - A number of the returns looked fine but occasionally I would see some problems in the output! So I looked at the problem and thought it was a printf issue, wrong! The printf function will print character strings using %s , but the character buffer returned by the Encryption API is filled with Hex ...
🌐
Bloomu
montcs.bloomu.edu › Information › C › printf-formatting.html
printf() formatting
The first argument to printf() ... as a conversion specification for each further argument. An example of this might be: printf( "hex number in wide field---> %#12x <---\n", 0x64 );...
Top answer
1 of 4
19

This:

printf("%x", array);

will most likely print the address of the first element of your array in hexadecimal. I say "most likely" because the behavior of attempting to print an address as if it were an unsigned int is undefined. If you really wanted to print the address, the right way to do it would be:

printf("%p", (void*)array);

(An array expression, in most contexts, is implicitly converted to ("decays" to) a pointer to the array's first element.)

If you want to print each element of your array, you'll have to do so explicitly. The "%s" format takes a pointer to the first character of a string and tells printf to iterate over the string, printing each character. There is no format that does that kind of thing in hexadecimal, so you'll have to do it yourself.

For example, given:

unsigned char arr[8];

you can print element 5 like this:

printf("0x%x", arr[5]);

or, if you want a leading zero:

printf("0x%02x", arr[5]);

The "%x" format requires an unsigned int argument, and the unsigned char value you're passing is implicitly promoted to unsigned int, so this is type-correct. You can use "%x" to print the hex digits a throughf in lower case, "%X" for upper case (you used both in your example).

(Note that the "0x%02x" format works best if bytes are 8 bits; that's not guaranteed, but it's almost certainly the case on any system you're likely to use.)

I'll leave it to you to write the appropriate loop and decide how to delimit the output.

2 of 4
8

This is what I did, its a little bit easier with a function and I use for debugging and logging memory.

void print_hex_memory(void *mem) {
  int i;
  unsigned char *p = (unsigned char *)mem;
  for (i=0;i<128;i++) {
    printf("0x%02x ", p[i]);
    if ((i%16==0) && i)
      printf("\n");
  }
  printf("\n");
}
🌐
Reddit
reddit.com › r/cprogramming › what's going on here with the output of printf hexadecimal
r/cprogramming on Reddit: What's going on here with the output of printf hexadecimal
December 27, 2023 - Just tell printf to treat it as unsigned chat and it would go away. ... Removing any sign extension like 0xFF & buffer[i] would also work. It might even be more understandable, in this context. ... Yeah, I know. I read the rest of the answers. However, sometimes you can't choose the data type for some other reason. You might be adding debug to existing code that needs to use plain char. If you are messing around at the hex level anyways, using bitwise operators (& | ^ << >>) can be more direct, and more adaptable, than dealing with implied type conversions.
🌐
Post.Byes
post.bytes.com › home › forum › topic
printf for a char in hex - why all the F's? - Post.Byes - Bytes
November 14, 2005 - On 2's complement machines this actually works, so you will get the same display as if you went: printf("%x", (unsigned int) foo); If you want to print a value between 0..255 , you would have to cast your char to an unsigned char before passing it to printf. (Strictly speaking, I think it should ...
🌐
IBM
ibm.com › docs › en › zos › 2.5.0
printf - Write formatted output
Get assistance for the IBM products, services and software you own · Provides fixes and updates for your system's software, hardware, and operating system
🌐
Reddit
reddit.com › r/c_programming › hex printing more than 2 characters?
r/C_Programming on Reddit: Hex printing more than 2 characters?
November 25, 2022 -

So i'm working on a mimic of the hexdump command in linux and for whatever reason some characters and printing properly and some are adding 6 "F" characters to the output and i'm not sure why. any insight is appreciated

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char input[20];
    char chr1;
    char chr2;
    char magNum[8] = {};
    char fType[4] = {};
    printf("Filename of binary to hexdump: ");
    scanf(" %s", input);
    FILE *hexFile = fopen(input, "r");
    if(hexFile == NULL)
    {
        printf("Unable to open the file\n");
        exit(1);
    }
    printf("\nMagic Number: ");
    int counter = 0;
    while((chr1 = fgetc(hexFile)) != EOF)
    {
        if(counter == 4)
        {
            break;
        }
        printf("%0X", chr1);
        fType[counter] = chr1;
        counter++;
    }
    printf(" FileType: %s\n", fType);

    printf("===============================================================================\n");
    printf("| Offset |                 Hexadecimal Data                  |Character Format|\n");
    printf("===============================================================================\n");  
    printf("| TestLne | AA AA AA AA AA AA AA AA   AA AA AA AA AA AA AA AA |.ELF............|\n");

    int lineCount = 0;
    char lineString[16] = {};
    fseek(hexFile, 0, SEEK_SET);
    while((chr2 = fgetc(hexFile)) != EOF)
    {
        printf(" %0X", chr2);
    }
    
    return 0;
}
🌐
CCS, Inc.
ccsinfo.com › forum › viewtopic.php
CCS :: View topic - RS232 printf - how do I send a hex value instead of ASCII
Profile Log in to check your private messages Log in · CCS does not monitor this forum on a regular basis