Dan
Dan

Reputation: 2344

Convert C++ byte array to a 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?

Upvotes: 8

Views: 50736

Answers (3)

gsamaras
gsamaras

Reputation: 73366

C strings are null terminated, so the size of the string will be the size of the array plus one, for the null terminator. Then you could use memcpy() to copy the string, like this:

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

typedef unsigned char BYTE;

int main(void)
{
  BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };

  // +1 for the NULL terminator
  char str[sizeof(byteArray) + 1];
  // Copy contents
  memcpy(str, byteArray, sizeof(byteArray));
  // Append NULL terminator
  str[sizeof(byteArray)] = '\0';

  printf("%s\n", str);    
  return EXIT_SUCCESS;
}

Output:

Hello

Run it online

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

Here is a demonstrative program that shows how it can be done.

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

typedef unsigned char BYTE;

int main(void) 
{
    BYTE byteArray[5] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
    char s[sizeof( byteArray ) + sizeof( ( char )'\0' )] = { '\0' };

    memcpy( s, byteArray, sizeof( byteArray ) );

    puts( s );

    return 0;
}

The program output is

Hello

Pay attention to that the character array is zero initialized. Otherwise after the call of memcpy you have to append the terminating zero "manually".

s[sizeof( s ) - 1] = '\0';

or

s[sizeof( byteArray )] = '\0';

The last variant should be used when the size of the character array much greater than the size of byteArray.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

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);
}

Upvotes: 19

Related Questions