Get Bytes from Std::String in C++

Get bytes from std::string in C++

If you just need read-only access, then c_str() will do it:

char const *c = myString.c_str();

If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then:

std::vector<char> bytes(myString.begin(), myString.end());
bytes.push_back('\0');
char *c = &bytes[0];

std::string to BYTE[]

You can use string::c_str() function which returns a pointer to c style string that can be passed to winapi functions like:

foo(string.c_str());

What it actually does is that it returns a pointer to an array that contains a null-terminated sequence of characters.


I suppose BYTE[] is actually a char array. You can assign your std::string to char array by doing:

std::string str = "hello";
BYTE byte[6]; // null terminated string;
strcpy(byte, str.c_str()); // copy from str to byte[]

If you want to copy the str without the 0 at the end, use strncpy instead:

BYTE byte[5];
strncpy(byte, str.c_str(), str.length());

Convert C++ byte array to a C string

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


Related Topics



Leave a reply



Submit