-1

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.

bibo
  • 3
  • 2

2 Answers2

2

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

Cyao
  • 727
  • 4
  • 18
  • 1
    You probably meant `%#.2x`? – Lundin Feb 09 '23 at 14:13
  • No, its `%#02x`, `0` means to use zeros to pad instead of spaces – Cyao Feb 09 '23 at 14:16
  • 1
    `printf("%#02x", 0x1);` prints `0x1`. `printf("%#.2x", 0x1);` prints `0x01`. – Lundin Feb 09 '23 at 14:18
  • 2
    opps should've been `%#04x`. I blame linux 0.0.1's printf for this (I usually use it's printf XD) – Cyao Feb 09 '23 at 14:21
  • Please read about the difference between the width and the precision specifier: https://en.wikipedia.org/wiki/Printf_format_string#Width_field or https://en.cppreference.com/w/c/io/fprintf – Bob__ Feb 09 '23 at 14:22
  • 1
    TBH learning all these hoops and quirks of printf format is pretty useless knowledge... That being said, the `04` means minimum field width (spaces, zeros, any character) of 4 and the `.2` means maximum digits 2. Zeroes instead of spaces is decided by the `%x` itself. The boring standard text is "For d, i, o, u, x, X, a, A, e, E, f, F, g, and G conversions, leading zeros (following any indication of sign or base) are used to pad to the field width rather than performing space padding," – Lundin Feb 09 '23 at 14:29
-1

printf("%#02x\r\n", pBuffer[0]) For some reason it don't prints anything without \r\n.

bibo
  • 3
  • 2