Javascript C# Unicode 字符串 - headscratcher
如果我使用以下方法将 Javascript 中的 Bytearray 转换为字符串:
convertByteArrayToString: function(byteArray)
{
var s = '';
for(var i = 0;i < byteArray.length;i++)
{
s += String.fromCharCode(byteArray[i])
}
return s;
},
如何将此字符串转换回 C# 中的字节数组?
我已经尝试了以下所有三个:
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);
最接近的是第一个,但它返回一个字节数组,该数组是原始长度的两倍,数组中的每个其他元素都是 0,有时是一个或两个不正确的值。
据我所知, String.fromCharCode 在 Unicode 中工作,那么如何让它与 C# 进行互操作呢?
这让我抓狂!
编辑:
这是一个示例,
原始字节数组: [139, 104, 166, 35, 8, 42, 216, 160, 235, 153, 23, 143, 105, 3, 24, 255]
我的函数将其转换为: "h...*Ø ëiÿ"
在 C# 中,尝试将此 String 解码为字节数组会产生以下结果:
使用 System.Text.UnicodeEncoding 给出: [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]
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
crypto-js 具有
Crypto.charenc.UTF8.stringToBytes() 和
Crypto.charenc.UTF8.bytesToString()
,它们与 C# 中的 UTF-8 编码完美配合。编辑
经过讨论,结果表明,OP 希望将
byte[]
从 JS 传输到 C# - 这最好通过base64
编码来完成(我推荐相同的JS工具包)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 viabase64
encoding (I recomend the same JS toolkit)