How to print numbers in HEX with printf in C?

How to print numbers in HEX with printf in C?

static void ReadReg_SI5338(uint8_t *pBuffer)
{
    uint8_t ret;
    ret = HAL_I2C_Master_Transmit(&hi2c2, SI5338_ADDR, pBuffer, 1, 5);
      if ( ret != HAL_OK )
      {
        printf("Error Tx\r\n");
      }
      else
      {
          ret = HAL_I2C_Master_Receive(&hi2c2, SI5338_ADDR, pBuffer, 1, 5);
          if ( ret != HAL_OK )
          {
              printf("Error Rx\r\n");
          }
          else
          {
              printf(pBuffer[0], "\r\n");
          }
      }
}

The code works, it reads correct values, but prints garbage in terminal. I’d like to have it in format "0x38", "0x01", etc. But i don’t know how to do it.

>Solution :

To print numbers in hex in C, use:

printf("%#04x", number);

#: means include a 0x before the number

04: mean padd the number with 2 zeros (aka if the number is 1, it will print 0x01 instead of 0x1, 4 cuz 2 for 0x)

x: hex specifier

Leave a Reply