how to include hex value in string using sprintf

c, hex, printf

Solution

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.

Problem

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....

Original source