is there any way to convert string to byte in c++ just like the getbytes() in java??
Printable View
is there any way to convert string to byte in c++ just like the getbytes() in java??
Like using the [ ] operator perhaps?
Code:#include <iostream>
#include <string>
#include <iomanip>
int main ( ) {
std::string foo = "hello";
std::cout << "Letter=" << foo[0] << std::endl;
}
Well, getBytes() returns an array of bytes, so I think the closest to that would be using string::c_str() to get a pointer and copy the characters to a new char array (or copy them using operator[]).
Or even better, use a vector like Elysia suggested below.Code:std::string str = "hello world";
char* cstr = new char [str.size() + 1];
std::strcpy(cstr, str.c_str());
//...
delete [] cstr;
Don't forget to delete that!
A better approach:
Code:std::string str = "Hello World";
std::vector<char> bytes(str.begin(), str.end());
thanks for the help and sorry for the late reply but i was thinking of a little something like this one
The output isCode:public class TestByte
{
public static void main(String[] argv) {
String example = "This is an example";
byte[] bytes = example.getBytes();
System.out.println("Text : " + example);
System.out.println("Text [Byte Format] : " + bytes);
}
}
Text : This is an example
Text [Byte Format] : [B@187aeca
is this possible to do in c++?
A "byte format" baffles me. You do realize that "[B@187aeca" is just a textual representation of the variable. "[B" means its an array of bytes, and the rest of it is probably an address. It's not what you'd get if you'd loop over the array and print it byte by byte.
So, you already have "bytes" available in a string trough operator[], and if you want to have an array or a vector of bytes/chars, then just use the code above. I fear, though, that you don't quite get the whole shebang with c-strings/char arrays and std::string in the first place. In this case I think you should read trough these:
Character Sequences - C++ Documentation
C Strings - C Tutorial - Cprogramming.com
Cprogramming.com - C++ Standard Library - String Class
thanks..not the answer i am looking for but it helps in another way..
Then what do you want? You have your array of bytes (examples above).
A Java String is a sequence of Java chars, which are UTF-16 codepoints. getBytes() without arguments takes the platform default encoding (some Windows-xxxx codepage under Windows, UTF-8 on most Unices) and converts the Unicode sequence to that encoding, returning the resulting data as a byte array.
A C++ std::string already is a sequence of bytes in the platform default encoding (strictly speaking, it's a sequence of bytes whose interpretation is up to you, but this is the way most library functions treat it), so your question makes no sense. There's nothing to convert.
Perhaps the best question is, what are you trying to do?