A string (char array) in C is a sequencial sequence of chars terminated by a sentianal character (the null terminator: '\0')

This means that if you have a byte of the value 0x00 anywhere in your array, it has thusly terminated the "string" potentially before the end of the sequence. In your example if you converted your data array into a string the end of it would be the first element:

data[]{00, EB, 23, EC, FF, etc... };

Now if you want to make a string out of the values of the data in here, you can do that with sprintf(), for example:

unsigned char val = 00;
data[0] = val;
char dump[5] = {0};

sprintf(dump, "%02x", data[0]);

Now you have a string with the value "00" in it, You can make it fancer with something like:

sprintf(dump, "0x%02x", data[0]);

So that it has "0x00" to show it off as hex data.

You could loop something like this to give the full string... but keep in mind that the printable string needs to be at least 2x+1 the size of the data string (2x for ASCII and +1 for null), and you have to fill the new string in steps. Example:

unsigned char data[5] = {0x00, 0x12, 0xB3, 0xFF, 0xF0};
char printstr[11] = {00};

for(int x = 0; x < 5; x++)
    sprintf(printstr+(x*2), "%02x", data[x]);
printstr[10] = '\0';

Now printstr has "0012b3fff0"

Answer from Mike on Stack Overflow
🌐
Reddit
reddit.com › r/learnprogramming › c++ : idiomatic way of creating string from unsigned char array
r/learnprogramming on Reddit: C++ : Idiomatic way of creating string from unsigned char array
March 9, 2022 -

I've found various different ways of creating strings from unsigned char arrays on StackOverflow etc, however, I couldn't discern the best / most idiomatic way of doing it. I need this for reading lines from memory mapped files.

string MemoryMappedReader::getLine() {
    // Null-terminated buffer.
    unsigned char buffer[_bufferSize];
    fill_n( buffer, _bufferSize, '\0' );

    for (int index = 0; (_cursor += index) < _fileSize; index++) {
        unsigned char character = _memoryMappedFile[_cursor];
        if (character == '\n')
            break;
        buffer[index] = character;
    }
    
    return ""; // I want to return  a string representation of buffer
}

Any advise?

Top answer
1 of 3
3

A string (char array) in C is a sequencial sequence of chars terminated by a sentianal character (the null terminator: '\0')

This means that if you have a byte of the value 0x00 anywhere in your array, it has thusly terminated the "string" potentially before the end of the sequence. In your example if you converted your data array into a string the end of it would be the first element:

data[]{00, EB, 23, EC, FF, etc... };

Now if you want to make a string out of the values of the data in here, you can do that with sprintf(), for example:

unsigned char val = 00;
data[0] = val;
char dump[5] = {0};

sprintf(dump, "%02x", data[0]);

Now you have a string with the value "00" in it, You can make it fancer with something like:

sprintf(dump, "0x%02x", data[0]);

So that it has "0x00" to show it off as hex data.

You could loop something like this to give the full string... but keep in mind that the printable string needs to be at least 2x+1 the size of the data string (2x for ASCII and +1 for null), and you have to fill the new string in steps. Example:

unsigned char data[5] = {0x00, 0x12, 0xB3, 0xFF, 0xF0};
char printstr[11] = {00};

for(int x = 0; x < 5; x++)
    sprintf(printstr+(x*2), "%02x", data[x]);
printstr[10] = '\0';

Now printstr has "0012b3fff0"

2 of 3
1

you can use sprintf (note if you sprintf past the end of the 'str' array, you will have a buffer overflow):

//malloc 2 chars for each byte of data (for 2 hex digits)
char *str = malloc(sizeof(char) * 3 * (sizeof(data) + 1));

//this var will point to the current location in the output string
char *strp = str;

if (NULL == str)
{
    return false; //memory error
}

for (size_t i= 0; i < sizeof(data); i++) {
    snprintf(strp, 2, "%02X ", data[i]);
    strp++;
}

// now the memory in *str holds your hex string!
Discussions

How do I pass an unsigned char * (an array of bytes representing binary data) from C to OCaml?
I have been able to pass a string argument to OCaml side from C side using a callback and caml_alloc_initialized_string as instructed here (OCaml - Interfacing C with OCaml). Now, I want to add a second argument: an array of bytes representing binary data. Is there a caml_alloc_ function I ... More on discuss.ocaml.org
🌐 discuss.ocaml.org
1
0
February 13, 2024
Convert unsigned char to String
Hi there, I’m having some trouble trying to convert an unsigned char to a string. I’m trying to covert dta into a string. Thanks in advance for any help int len = 0; unsigned char dta[20]; while(Serial1.available()) { dta[len++] = Serial1.read(); } //convert dta into a string here More on community.particle.io
🌐 community.particle.io
0
0
February 19, 2015
How to convert a string literal to unsigned char array in visual c++ - Stack Overflow
And even if you had the direction ... char array, not an unsigned char. ... Sign up to request clarification or add additional context in comments. ... Maybe worth mentioning that you can drop the size in the last example, since the compiler will figure it out. 2010-02-05T09:54:04.11Z+00:00 ... For all practical purposes, the strcpy answers are correct, with the note that 8 isn't big enough for your string... More on stackoverflow.com
🌐 stackoverflow.com
c++ - Copying non null-terminated unsigned char array to std::string - Stack Overflow
However, I wonder what is the most appropriate way to copy a non null-terminated unsigned char array, like the following: unsigned char u_array[4] = { 'a', 's', 'd', 'f' }; ... Thank you all. ... std::string has a constructor that takes a pair of iterators and unsigned char can be converted ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
OCaml
discuss.ocaml.org › learning
How do I pass an unsigned char * (an array of bytes representing binary data) from C to OCaml? - Learning - OCaml
February 13, 2024 - I have been able to pass a string argument to OCaml side from C side using a callback and caml_alloc_initialized_string as instructed here (OCaml - Interfacing C with OCaml). Now, I want to add a second argument: an arr…
🌐
Particle
community.particle.io › general
Convert unsigned char to String - General - Particle
February 19, 2015 - Hi there, I’m having some trouble trying to convert an unsigned char to a string. I’m trying to covert dta into a string. Thanks in advance for any help int len = 0; unsigned char dta[20]; while(Serial1.available()) { dta[len++] = Serial1.read(); } //convert dta into a string here
🌐
GitHub
gist.github.com › miguelmota › 9837dc763da3bb507725251b40f6d863
C++ unsigned char array to string · GitHub
C++ unsigned char array to string. GitHub Gist: instantly share code, notes, and snippets.
🌐
DigitalOcean
digitalocean.com › community › tutorials › convert-string-to-char-array-c-plus-plus
Convert String to Char Array and Char Array to String in C++ | DigitalOcean
August 3, 2022 - At first, we use c_str() method to get all the characters of the string along with a terminating null character. Further, we declare an empty array of type char to store the result i.e.
Find elsewhere
🌐
Cprogramming
cboard.cprogramming.com › cplusplus-programming › 67790-convert-`const-unsigned-char-[]-`std-string.html
Convert `const unsigned char []' to `std::string'
#include <string> int main() { const unsigned char[] cbuffer = { 0x61, 0x62, 0x63, 0x0 }; std::string sbuffer; sbuffer = const_cast<std::string> (cbuffer); return 0; } Last edited by cboard_member; 07-18-2005 at 04:22 AM. Good class architecture is not like a Swiss Army Knife; it should be more like a well balanced throwing knife. - Mike McShaffry ... the only way i can think out is to assign cbuffer to a char array, and then use the char array to initialize the string
🌐
GitHub
gist.github.com › dlwhitehurst › 6aff1dc85205315e59d5b60e702681b2
Convert unsigned char array to string · GitHub
Convert unsigned char array to string · Raw · gistfile1.txt · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
How create a String from an 'unsigned char' array? - Programming - Arduino Forum
July 23, 2021 - And if I try to create a String from the 'unsigned char' array I get the error: invalid conversion from 'unsigned char' to 'const char*'*. unsigned char* base64 = (unsigned char*)heap_caps_malloc(4*(_jpg_buf_len/3)+1, MALLOC_CAP_8BIT); if (base64 == NULL) Serial.p...
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › convert-character-array-to-string-in-c
Convert character array to string in C++ - GeeksforGeeks
July 11, 2025 - Method 3: Another way to do so would be to use an overloaded '=' operator which is also available in the C++ std::string. Approach: Get the character array and its size.
🌐
Cplusplus
cplusplus.com › forum › general › 144033
How do I convert an 'unsigned char' to ' - C++ Forum
October 4, 2014 - OK, I have a variable of type unsigned ... unsigned char to std::string please see the example below. unsigned char myVar[10] = "abcdefg" I want to convert the variable above to type std::string. ... You have array, not a single char....
Top answer
1 of 1
4

C strings, one of many ways one could represent a string, consist of arrays of char terminated by a trailing char which has the null value. That's what you get type-wise when you have "0000" in your code.

What you want is to assign "0000" to be an array of unsigned char terminated by a trailing unsigned char which has the null value. Considering what you are starting with, you will have to cast, or perhaps represent your initial data in a manner that doesn't require casting.

unsigned char T[][] = { { 0x30, 0x30, 0x30, 0x30, 0x00 }, 
               { 0x30, 0x30, 0x30, 0x31, 0x00 }, 
               { 0x30, 0x30, 0x31, 0x30, 0x00 }, 
               { 0x30, 0x30, 0x31, 0x31, 0x00 }, 
               { 0x30, 0x31, 0x30, 0x30, 0x00 }, 
               { 0x30, 0x31, 0x30, 0x31, 0x00 }, 
               { 0x30, 0x31, 0x31, 0x30, 0x00 }, 
               { 0x30, 0x31, 0x31, 0x31, 0x00 }, 
               { 0x31, 0x30, 0x30, 0x30, 0x00 }, 
               { 0x31, 0x30, 0x30, 0x31, 0x00 }, 
               { 0x31, 0x30, 0x31, 0x30, 0x00 }, 
               { 0x31, 0x30, 0x31, 0x31, 0x00 }, 
               { 0x31, 0x31, 0x30, 0x30, 0x00 }, 
               { 0x31, 0x31, 0x30, 0x31, 0x00 }, 
               { 0x31, 0x31, 0x31, 0x30, 0x00 }, 
               { 0x31, 0x31, 0x31, 0x31, 0x00 }
              };

The main problem I see with this approach is that it removes most of the advantage of having a C style string in the first place. With an unsigned char "string", you have none of the standard string libraries at your disposal, so you will have to cast back to signed char string types if you want to use printf, or any other string oriented function.

Really, you are only using two values for each possible character position "0" and "1". Unless there is a compelling reason to do it in a string, consider an array of boolean values to reduce the chance of a string like "0hello" working it's way into the code, or better yet if you have been introduced to bit fields, use the bits within an unsigned char as bit fields (discarding any concept that you're dealing with strings).

The advantages to the last technique include using less memory and the inability for the value to be other than 0 or 1; however, you will have to write a small collection of routines to translate the packed bits into something human readable.

unsigned char[] = { 0x00, 0x01, 0x02, 0x03, 0x04,
                    0x05, 0x06, 0x07, 0x08, 0x09,
                    0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
                    0x0F };

void displayChar(unsigned char value) {
  switch (value) {
    case 0x00: printf("0000"); break;
    case 0x01: printf("0001"); break;
    case 0x02: printf("0010"); break;
    case 0x03: printf("0011"); break;
... and so on ...
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › c › STR34-C.+Cast+characters+to+unsigned+char+before+converting+to+larger+integer+sizes
STR34-C. Cast characters to unsigned char before converting to larger integer sizes - SEI CERT C Coding Standard - Confluence
In fact, to prevent sign extension, a char value must be cast to unsigned char. For example, in the non-compliant example below the result of the cast of *s to unsigned int may result in a value in excess of UCHAR_MAX due to integer promotion, thus causing the function to violate ARR30-C. Guarantee that array indices are within the valid range, leading to undefined behavior.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Converting const unsigned Char* to String - Programming - Arduino Forum
August 17, 2017 - Hi, i'm trying to use a BLE Characteristic to tell my Arduino what to do. The BLE Characteristic is a 20 Byte const unsigned Char pointer. How can i convert it or read it ? I'm using the CurieBLE.h on a Arduino 101 to communicate over BLE. const unsigned char* tempchar = Choose.value(); // Choose is the BLE Characteristic String tempstring = tempchar; // thats the problematic line invalid conversion from 'const unsigned char*' to 'const char*' [-fpermissive]