How to convert string to byte array and vice versa?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yabansu
    New Member
    • Dec 2006
    • 14

    How to convert string to byte array and vice versa?

    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:

    Code:
    string msg = "Hello!";
    byte[] buffer = new byte[msg.Length];
    
    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
    buffer = encoding.GetBytes(msg);
    What is the C++ way of doing the same thing as .NET GetBytes method did?

    Thanks at all,
    yabansu
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    you can use the c_str() function in <string> to get a const pointer to an array of char, e.g.
    Code:
        const char * ch=s.c_str();
        cout << ch << endl;
    see http://www.cppreferenc e.com/cppstring/index.html

    Comment

    • asdfghjkl2007
      New Member
      • Oct 2006
      • 30

      #3
      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_arra y[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;
      }
      }
      }

      Comment

      Working...