Search code examples
cmicrocontrollerledlcd

sprintf puts FF infront without any reason in C


I have this weird problem where I am using sprintf and it puts FF in front of the value I have.

(e.g.) I should get 01, but I am getting FF01

My code looks like this

while(1)
{

    if(getkey()=='g')
    {
       sprintf(str_2, "%X", ~OWReadByte());
       lcd_delay();
       lcd_string(str_2);
    }
}

I did some checking on the LEDs and on there i get the value i want, after using sprintf it just gets screwed up.


Solution

  • The unary ~ operator changes the bits of the whole int, not only the lower 8 bits. ~0xfeu (equivalently, ~0x00feu) is 0xff01u for 16-bit int.

    I suggest to always use unsigned types when doing bit manipulation, passing a negative int to %X is, strictly speaking, undefined behavior.

    To get rid of the higher bits, you can do

    sprintf(&str_2[i * 2], "%02X", ~OWReadByte() & 0xffu);