If I convert a Bytearray in Javascript to a string using the following method:
convertByteArrayToString: function(byteArray)
{
var s = '';
for(var i = 0;i < byteArray.length;i++)
{
s += String.fromCharCode(byteArray[i])
}
return s;
},
How do I then convert this string back to a byte array in C#?
I have tried all three of the following:
System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding().GetBytes(myString);
System.Text.UTF32Encoding encoding = new System.Text.UTF32Encoding().GetBytes(myString);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding().GetBytes(myString);
The closest is the first one, but it returns a Byte array which is double the length of the original with every other element in the array being 0 and sometimes an incorrect value or two.
As far as I am aware, the String.fromCharCode works in Unicode, so how do get this to interoperate with C#?
This is driving me nuts!
Edit:
Here is an example,
Original Byte array:
[139, 104, 166, 35, 8, 42, 216, 160, 235, 153, 23, 143, 105, 3, 24, 255]
My function converts this to:
“h¦#*Ø ëiÿ”
In C#, attempting to decode this String to a byte array yields the following results:
Using System.Text.UnicodeEncoding gives:
[142,0,139,0,104,0,166,0,35,0,8,0,42,0,216,0,32,0,235,0,153,0,23,0,143,0,105,0,30,24,0,255,0]
crypto-js has
Crypto.charenc.UTF8.stringToBytes()andCrypto.charenc.UTF8.bytesToString(), that werk perfectly with UTF-8 encoding in C#.Edit
After discussion it turns out, the OP wants to transport a
byte[]from JS into C# – this is better done viabase64encoding (I recomend the same JS toolkit)