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
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!
🌐
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
Discussions

C++ how to convert unsigned char array to string? - Stack Overflow
I'm testing a piece of code that performs a hash operation (sha256) of a binary file and I've got something like this: for(i = 0; i More on stackoverflow.com
🌐 stackoverflow.com
converting unsigned char array to char array
The cast you'd want is: for(z =0; ... from an unsigned char. ... > The assignment to c works fine without the cast. By which I mean you get the negative character, which I assume you intended to get - i.e. 0xD0 -> -81 ... Hi rstaveley and VCStud, Thanks for HELP ... working quite fine. But the main problem is i want to pass this char array as string to some other ... More on experts-exchange.com
🌐 experts-exchange.com
October 3, 2011
How do I convert an 'unsigned char' to ' - C++ Forum
How would you convert a single character to the several? Describe what you have and what are you want to achieve. Preferrably with examples. ... OK, I have a variable of type unsigned char; this variable contains a once word string. So I want to convert this variable from the type unsigned ... More on cplusplus.com
🌐 cplusplus.com
October 4, 2014
Convert C unsigned char to string
I'm looking toconvert this C code into LabVIEW. I'm a bit confused on how to load the SendData into my .so or .dll (for windows). The CPCI75C3_SER_TransmitBuffer function provided takes in a string. How do I convert this array of unsigned char to a string? unsigned char SendData[8]; ...... More on forums.ni.com
🌐 forums.ni.com
1
0
May 25, 2012
🌐
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?

🌐
GitHub
gist.github.com › miguelmota › 9837dc763da3bb507725251b40f6d863
C++ unsigned char array to string · GitHub
C++ unsigned char array to string · Raw · char_to_string.cpp · 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.
🌐
Experts Exchange
experts-exchange.com › questions › 20746033 › converting-unsigned-char-array-to-char-array.html
Solved: converting unsigned char array to char array | Experts Exchange
October 3, 2011 - The cast you'd want is: for(z =0; z < 10;z++) printf("x",*(unsigned char*)&ctemp[z]); This way the integer promotion is from an unsigned char. ... > The assignment to c works fine without the cast.
🌐
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
🌐
Cplusplus
cplusplus.com › forum › general › 144033
How do I convert an 'unsigned char' to ' - C++ Forum
October 4, 2014 - So I want to convert this variable from the type 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. MiiNiPaa (8886) You have array, not a single char. AceK (61) that doesn't work either. MiiNiPaa (8886) It does: http://coliru.stacked-crooked.com/a/196005524662db21 http://ideone.com/ORdzm1 YOu just might do something wrong.
Find elsewhere
🌐
CodeProject
codeproject.com › Questions › 1053605 › how-to-convert-unsigned-char-array-to-String
how to convert unsigned char array to String^ - CodeProject
November 10, 2015 - Free source code and tutorials for Software developers and Architects.; Updated: 10 Nov 2015
🌐
Experts Exchange
experts-exchange.com › questions › 21010454 › Converting-std-string-to-unsigned-char.html
Solved: Converting std::string to unsigned char | Experts Exchange
June 2, 2004 - Hi yawnb, You can convert a std::string to a C string (using the c_str() method), which can be cast to an unsigned C string: unsigned char* uc = (unsigned char*)myString.c_str(); bronkbronk ·
🌐
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
The problem is not that the comparison might fail, it is that s might be an invalid array index (if converted from plain char to int). This is especially likely if s is EOF (or some other signed char less than 0). ... Yes, I see. I meant the char array itself table[(unsigned char)*s] and *s (right of != ) should also be non-compliant case.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
How to store value into unsigned char array [SOLVED] - Programming - Arduino Forum
January 23, 2018 - Hi guys, So, I am doing a LEDs Pixel Display now, using 100 WS2811 LEDs, FastLED and LEDText libraries. FastLED: GitHub - FastLED/FastLED: The FastLED library for colored LED animation on Arduino. Please direct questions/requests for help to the FastLED Reddit community: http://fastled.io/r ...
🌐
openFrameworks
forum.openframeworks.cc › beginners
Converting string to unsigned char - beginners - openFrameworks
November 11, 2009 - Hi there, I’m working on a ofxSimpleSerial-addon and because people like to work with strings I would like to add a writeString() method. But… I don’t understand how I should convert strings into unsigned char’s, and t…
🌐
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 - C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
How create a String from an 'unsigned char' array? - Programming - Arduino Forum
July 23, 2021 - I'm working on a mesh where every node take a picture, encode it in base64 and send the result to the root node. The encoded array is 'unsigned char' but the function used to send the data to the root node via mesh accepts a String. 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...
🌐
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]