1

I want to convert byte array uint8_t Hexadecimal values to char array string (**same values not ASCII) and then simple print this string array as below:

input:

uint8_t myarr[4]={0x11,0x12,0x33,0x1A}

output:

 1112331A

Simple char array string not hexadecimal array string.

3
  • What you are asking for is often called "hex dump", if I understand your question correctly. Google "hex dump c" or something to get examples. If you are having trouble with this, try to expand the question more with your own code, because a lot of things depends on what you actually want. Commented Jan 10, 2019 at 11:12
  • Short code to get your desired output: for(int i=0; i<4; ++i) printf("%02X", myarr[i]); . If you actually want a string, it gets a bit more complicated of course, because of how C does strings, and needs those extra details missing from the question. Commented Jan 10, 2019 at 11:13
  • What is a "hexadecimal array string"? A string always is a sequence of single characters that is terminated by a 0 byte. Commented Jan 10, 2019 at 11:19

2 Answers 2

7

Just loop over the elements of the array and use printf to print each element using the "%hhx" format specifier.

Also note that the values will not be stored as hexadecimal. Hexadecimal is just a form to present values.

Sign up to request clarification or add additional context in comments.

6 Comments

I was just gonna say %hhx. Nice.
Since this is not scanf, does the %hhx make any sense? The function will receive an int anyway (it's a variable arguments function), so %x or %02x should be ok. Do I miss something?
@CostantinoGrana Yes, a signed int with possible sign extension.
The correct format string is actually "%" PRIx8 from inttypes.h.
@Someprogrammerdude Sorry, my comment was missing unsigned. Since the original datum is a uint8_t, shouldn't it be promoted to an unsigned int? Example: ideone.com/1VlMGv and godbolt.org/z/qWIkCx.
|
2

The old school way of raw data to ASCII hex conversion, is to use a look-up table based on nibbles:

#include <stdint.h>
#include <stdio.h>

int main (void)
{
  uint8_t myarr[4]={0x11,0x12,0x33,0x1A};
  char hexstr[4][2+1] = {0};

  const char HEX [16] = "0123456789ABCDEF";
  for(size_t i=0; i<4; i++)
  {
    hexstr[i][0] =  HEX[ (myarr[i] & 0xF0) >> 4 ];
    hexstr[i][1] =  HEX[ (myarr[i] & 0x0F) ];
    puts(hexstr[i]);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.