This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Incorrect work of the sprintf function

char str [4];

sprintf (str, "%.2x", 0x01);//Conversion of byte to the 2nd bit hexadecimal value

I expect in str[0] 0 character, in str[1] 1 character, that is '0' and '1'.
As a result function returns '1' and 'C'.
Remaining numbers - it is normal...

Parents
  • The reason is, that you only give ONE byte as value (0x01) and %x expects a TWO byte value.

    Total and absolute rubbish!

    If you want to get 2 digits from sprintf, you need to change it to

    sprintf (str, "%2.2x", 0x01)
    


    Separate note: This is such a strange forum, I was told my message was in error because it contained the spam word Wod. Took me too long to notice it was embedded in "two digits".

    Maybe I'm naive, but i don't see why that word would be considered spam.

Reply
  • The reason is, that you only give ONE byte as value (0x01) and %x expects a TWO byte value.

    Total and absolute rubbish!

    If you want to get 2 digits from sprintf, you need to change it to

    sprintf (str, "%2.2x", 0x01)
    


    Separate note: This is such a strange forum, I was told my message was in error because it contained the spam word Wod. Took me too long to notice it was embedded in "two digits".

    Maybe I'm naive, but i don't see why that word would be considered spam.

Children