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
How to Declare Variables of Different Types in the Initialization of a for Loop
How to Get the Mouse Position in a Console Program
How to Optimize Matrix Multiplication (Matmul) Code to Run Fast on a Single Processor Core
Is There Any C/C++ Library to Connect with a Remote Ntp Server
Why Does This If Condition Fail for Comparison of Negative and Positive Integers
How to Update Gcc in Mingw on Windows
Cmake: Failed to Run Msbuild Command: Msbuild.Exe
How to Read from a Text File, Character by Character in C++
Boost::Spirit Expression Parser
Why Does My Program Hang When Opening a Mkfifo-Ed Pipe
How to Use Cin.Fail() in C++ Properly
Comparison Between String Literal