Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading