Vybhavi Rs Vybhavi Rs - 6 months ago 49
C# Question

How to encode the string to UTF16BE format in c#

I have string --"प्रिय ग्राहक, आप कैसी हैं"

I want to encode this string to UTF16BE format so that I can pass the message to send sms using route mobile api

http:// <server>:8080/bulksms/bulksms?
username=---&password=---&type=2&dlr=0&destination=---&sourc
e=---&message=00440065006D006F0020004D006500730073006100670065
002100210021


I want the encoded message to be in this format(00440065006D006F0020004D006500730073006100670065002100210021)

Any help would be appreciated

Answer Source

The simplest way is:

string str = "Hello world";

string output = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(str)).Replace("-", string.Empty)

The inverse is a little more complex:

// http://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array
public static byte[] StringToByteArray(string hex)
{
    return Enumerable.Range(0, hex.Length)
                        .Where(x => x % 2 == 0)
                        .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                        .ToArray();
}

and then

// Demo Message!!!
string str2 = "00440065006D006F0020004D006500730073006100670065002100210021";
byte[] bytes2 = StringToByteArray(str2);
string input = Encoding.BigEndianUnicode.GetString(bytes2);