Shihab
Shihab

Reputation: 543

how to include hex value in string using sprintf

i want to include value of i hex format in c.

for(i=0;i<10;i++)
   sprintf(s1"DTLK\x%x\xFF\xFF\xFF\xFF\xFF\xFF",i);

but the above code outputs an error: \x used with no following hex digits

Pls any one suggest me a proper way....

Upvotes: 6

Views: 6011

Answers (4)

glglgl
glglgl

Reputation: 91029

Supposing you don't want to literally have \x00..\x0A, but the corresponding byte, you need

sprintf(s1, "DTLK%c\xFF\xFF\xFF\xFF\xFF\xFF",i);

while inserting \x%x would be at the wrong abstraction level...

If, OTOH, you really want to literally have the hex characters instead of the bytes with the named hey characters as their representation, the other answers might be more helpful.

Upvotes: 2

user1925921
user1925921

Reputation: 120

sprintf(s1"DTLK\\x%x\xFF\xFF\xFF\xFF\xFF\xFF",i);
//              ^------- Here

Depending on what output you would like to achieve, you may need to escape the remaining slashes as well.

Currently, the snippet produces a sequence of six characters with the code 0xFF. If this is what you want, your code fragment is complete. If you would like to see a sequence of \xFF literals, i.e. a string that looks like \x5\xFF\xFF\xFF\xFF\xFF\xFF when i == 5, you need to escape all slashes in the string:

sprintf(s1"DTLK\\x%x\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF",i);

//              ^    ^    ^    ^    ^    ^    ^

Finally, if you would like the value formatted as a two-digit hex code even when the value is less than 16, use %02x format code to tell sprintf that you want a leading zero.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You need to escape the slash on front of the \x:

sprintf(s1"DTLK\\x%x\xFF\xFF\xFF\xFF\xFF\xFF",i);
//              ^------- Here

Depending on what output you would like to achieve, you may need to escape the remaining slashes as well.

Currently, the snippet produces a sequence of six characters with the code 0xFF. If this is what you want, your code fragment is complete. If you would like to see a sequence of \xFF literals, i.e. a string that looks like \x5\xFF\xFF\xFF\xFF\xFF\xFF when i == 5, you need to escape all slashes in the string:

sprintf(s1"DTLK\\x%x\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF",i);
//              ^    ^    ^    ^    ^    ^    ^

Finally, if you would like the value formatted as a two-digit hex code even when the value is less than sixteen, use %02x format code to tell sprintf that you want a leading zero.

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

\x expects a hex value like \xC9.

If you want to include \x in your output, you need to escape \ with \\:

sprintf(s1"DTLK\\x%x\xFF\xFF\xFF\xFF\xFF\xFF",i);

Upvotes: 0

Related Questions