2

I have a char array composed of hex values that looks similar to this:

 char str[] =
        "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
        "\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
        "\x80\xe8\xdc\xff\xff\xff";

After manipulating this string, I want to fprintf this string to a file using this statement:

fprintf(fp, "%X\n", str);

but I'm getting an output similar to this:

65C58A20

Seems like it got condensed to a single hex number. How can I fprintf the str in the same form I declared it above, with separate hex values for each individual byte?

8
  • Might sprintf() work? Use it to convert the char array to a string, then print out that string to file instead? Commented Jan 24, 2017 at 0:37
  • Why %X?! Did you read the manual for printf? Commented Jan 24, 2017 at 0:38
  • 1
    fprintf(fp, "%02X\n", (unsigned char)str[index]); Commented Jan 24, 2017 at 0:39
  • 1
    @TheEyesHaveIt: See my updated answer. I'm assuming you want to print the same textual representation that was part of your source code back out as a string (as opposed to writing the actual bytes that are described by your source code). Commented Jan 24, 2017 at 0:45
  • 1
    Suggest editing "\x80\xe8\xdc\xff\xff\xff --> "\x80\xe8\xdc\xff\xff\xff"; (add last 2 characters, if that is what you meant. Commented Jan 24, 2017 at 0:53

1 Answer 1

2

What you need is this:

for (size_t i = 0; i != sizeof str - 1; ++i)
    fprintf(fp, "\\x%02x", (unsigned char)str[i]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.