By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,128 Members | 1,059 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,128 IT Pros & Developers. It's quick & easy.

How to convert string to byte array and vice versa?

yabansu
P: 14
Hi all,

This is my first message!

Using C++ standard libraries, I want to convert a string to a byte array and a byte array to the string. How can I do that?

I did it in C# .NET as the following:

Expand|Select|Wrap|Line Numbers
  1. string msg = "Hello!";
  2. byte[] buffer = new byte[msg.Length];
  3.  
  4. System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  5. buffer = encoding.GetBytes(msg);
What is the C++ way of doing the same thing as .NET GetBytes method did?

Thanks at all,
yabansu
Dec 25 '06 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 1,510
you can use the c_str() function in <string> to get a const pointer to an array of char, e.g.
Expand|Select|Wrap|Line Numbers
  1.     const char * ch=s.c_str();
  2.     cout << ch << endl;
  3.  
see http://www.cppreference.com/cppstring/index.html
Dec 25 '06 #2

P: 30
string s="0a"; ////string that should be converted to a bit_array
unsigned short int byte_array[100];
unsigned short int b[8];// used for storring the binary form of x=(int)s[i];
int x;

//converting a string to an array
int i=0;
int h=0;
while(s[i])
{
x=(int)s[i]; // converts a char to its int form
for(int j=0;j<8;++j)
{ // b[] stors the binary form of x but backwords
b[j]=x%2;
x=x/2;
}

for(int j=7;j>-1;--j)
{
byte_array[h]=b[j]; //adds b to byte_array[] but in the right way
++h;
}

++i;
}


////convert to string
// i supouse the array contoins elements
int j;
i=0;
cout<<" byte_array lenght = ?";
cin>>i; // you have to know the number of elements

string st=""; // empty string
if((i%8)==1) cout<<"error the array can't be converted to a string because the number of bits ins't a 8*K number";
// a char is represented by 8 bits so to be able to convet byte_array to a array of char ( a strig ) the number of
// elements of byte_array must be a multipal of 8 ( 8*K number k is an unsignedint)
else
{
h=0;
j=0;
x=0;
while(h<i)
{
x=x*2+byte_array[h]; // converting a grup af 8 bits to a int wich reprezent the code of a char
++h;
++j;
if(j==8)
{
j=0;
st=st+(char)x; //storing it in the string
x=0;
}
}
}
Dec 25 '06 #3

Post your reply

Sign in to post your reply or Sign up for a free account.