C#ByteArray的串转换和背部 [英] C# ByteArray to string conversion and back

查看:126
本文介绍了C#ByteArray的串转换和背部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要表示为ByteArray,并在一个字符串转换一个uint值。
当我字符串转换回一个字节数组,我发现不同的值。
我使用的是标准的ASCII转换器,所以我不明白为什么我得到不同的值。
更清晰,这是我在做什么:

 字节[] = bArray BitConverter.GetBytes(( UINT)49694); 
字符串测试= System.Text.Encoding.ASCII.GetString(bArray);
的byte []结果= Encoding.ASCII.GetBytes(试验);



的ByteArray结果是从第一个不同:



bArray - >

  [00000000]:0X1E 
[00000001]:为0xC2
[ 0x00000002]:为0x00
[0x00000003]:为0x00

结果 - >

  [00000000]:0X1E 
[00000001]:0x3F的
[0x00000002]:为0x00
[0x00000003]: 0×00

注意,字节1是在两个数组不同。



感谢您的支持。



问候


解决方案

 字符串测试= System.Text.Encoding.ASCII.GetString(bArray); 
的byte []结果= Encoding.ASCII.GetBytes(试验);

由于原始数据的不是ASCII Encoding.GetString 唯一有意义如果您正在解码数据的是该编码的文本数据的。还有什么:你腐败了。如果你想存储字节[] 字符串,然后基地-N是必要的 - 通常是基64因为:它是方便可用的(转换{要|从} Base64String ),和b:你能适应它成ASCII码,所以你很少打代码页/编码的问题。例如:

 字节[] = bArray BitConverter.GetBytes((UINT)49694); 
字符串测试= Convert.ToBase64String(bArray); //HsIAAA ==
的byte []结果= Convert.FromBase64String(试验);


I have a uint value that I need to represent as a ByteArray and the convert in a string. When I convert back the string to a byte array I found different values. I'm using standard ASCII converter so I don't understand why I'm getting different values. To be more clear this is what I'm doing:

byte[] bArray = BitConverter.GetBytes((uint)49694);
string test = System.Text.Encoding.ASCII.GetString(bArray);
byte[] result = Encoding.ASCII.GetBytes(test);

The bytearray result is different from the first one:

bArray ->

[0x00000000]: 0x1e
[0x00000001]: 0xc2
[0x00000002]: 0x00
[0x00000003]: 0x00

result ->

[0x00000000]: 0x1e
[0x00000001]: 0x3f
[0x00000002]: 0x00
[0x00000003]: 0x00

Notice that the byte 1 is different in the two arrays.

Thanks for your support.

Regards

解决方案

string test = System.Text.Encoding.ASCII.GetString(bArray);
byte[] result = Encoding.ASCII.GetBytes(test);

Because raw data is not ASCII. Encoding.GetString is only meaningful if the data you are decoding is text data in that encoding. Anything else: you corrupt it. If you want to store a byte[] as a string, then base-n is necessary - typically base-64 because a: it is conveniently available (Convert.{To|From}Base64String), and b: you can fit it into ASCII, so you rarely hit code-page / encoding issues. For example:

byte[] bArray = BitConverter.GetBytes((uint)49694);
string test = Convert.ToBase64String(bArray); // "HsIAAA=="
byte[] result = Convert.FromBase64String(test);

这篇关于C#ByteArray的串转换和背部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆