none
How to convert from unsigned char * to System.String?

    Question

  • Hi,

     

    I have an unsigned char * and need to convert it into a String. I have been searching around for quite a while without finding anything. Can I do that? If so, how do I do it?

     

    Here is what I want to do:

     

    unsigned char u_buf[15] = "this is my test";

    String * msg;

     

    I want msg to hold the string value pointed to by u_buf. How do I do that?

     

    Thanks!

     

    Feng

    Thursday, January 17, 2008 11:17 PM

Answers

  • System::String has a constructor that takes a char*, so just call that. A few notes, however:

    1. u_buf should be an unsigned char[16] in your example, as you're not allowing room for the implicit trailing null terminiator.
    2. String's constructor takes a signed char, not unsigned, so you need to cast your unsigned char* to a char*.
    3. System::String is a managed type, so you must use ^ instead of * like so:

      const unsigned char u_buf[16] = "this is my test";
      String^ msg = gcnew String(reinterpret_cast<const char*>(u_buf));
    • Edited by ildjarn Friday, August 05, 2011 8:15 PM
    Thursday, January 17, 2008 11:38 PM

All replies

  • System::String has a constructor that takes a char*, so just call that. A few notes, however:

    1. u_buf should be an unsigned char[16] in your example, as you're not allowing room for the implicit trailing null terminiator.
    2. String's constructor takes a signed char, not unsigned, so you need to cast your unsigned char* to a char*.
    3. System::String is a managed type, so you must use ^ instead of * like so:

      const unsigned char u_buf[16] = "this is my test";
      String^ msg = gcnew String(reinterpret_cast<const char*>(u_buf));
    • Edited by ildjarn Friday, August 05, 2011 8:15 PM
    Thursday, January 17, 2008 11:38 PM
  • Thank you so much for the answer!!!

     

    Feng

    Thursday, January 17, 2008 11:41 PM