Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert C++ byte array to a C string

Tags:

c++

arrays

c

string

I'm trying to convert a byte array to a string in C but I can't quite figure it out.

I have an example of what works for me in C++ but I need to convert it to C.

The C++ code is below:

#include <iostream>
#include <string>

typedef unsigned char BYTE;

int main(int argc, char *argv[])
{
  BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
  std::string s(reinterpret_cast<char*>(byteArray), sizeof(byteArray));
  std::cout << s << std::endl;

  return EXIT_SUCCESS;
}

Can anyone point me in the right direction?

like image 456
Dan James Palmer Avatar asked Jun 08 '26 15:06

Dan James Palmer


1 Answers

Strings in C are byte arrays which are zero-terminated. So all you need to do is copy the array into a new buffer with sufficient space for a trailing zero byte:

#include <string.h>
#include <stdio.h>

typedef unsigned char BYTE;

int main() {
    BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
    char str[(sizeof byteArray) + 1];
    memcpy(str, byteArray, sizeof byteArray);
    str[sizeof byteArray] = 0; // Null termination.
    printf("%s\n", str);
}
like image 118
Konrad Rudolph Avatar answered Jun 10 '26 03:06

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!