C#将字符串转换成其byte []等价物 [英] C# convert string into its byte[] equivalent

查看:136
本文介绍了C#将字符串转换成其byte []等价物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这一点上,大多数人都会以为这个不好的帖子..:

At this point most people will be thinking "Ah ill post this..:"

byte[] dataB= System.Text.Encoding.ASCII.GetBytes(data);

但是,我遇到的问题是我需要具有无编码的字节的确切值每个字节的纯值。例如,如果字符串的值为(0xFF32),我希望它也转换为{255,50}。他的原因是我有一个文件格式,我试图读取哪些存储int的字节保存,然后在程序打开时读取。

However.. the problem I have is i need the exact value of the bytes with no encoding just the pure value for each byte. For example if the value of the string is (0xFF32) i want it to convert it too {255,50}. he reason for this is I have a file format I am attempting to read which stores int's as bytes saves them and then reads them when the program opens.

这是我到目前为止:

...
dialog.InitialDirectory =
    Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) +
    "/Test";

dialog.Title="Open File";

if (dialog.ShowDialog(this) == DialogResult.OK)
{
    StreamReader reader = new StreamReader(dialog.FileName);
    string data = reader.ReadToEnd();
    reader.Close();
    byte[] fileC = System.Text.Encoding.ASCII.GetBytes(data);
    File_Read(dialog.FileName,fileC);
}
...

所以当我尝试读取文件将0xFF的文件修复程序转换为0x3F,因为0xFF大于127,0x3F为?。

So when I try and read the file it converts the file convents of say 0xFF into 0x3F because 0xFF is greater then 127 and 0x3F is a ?.

对不起,如果我有点混乱:)

Sorry if i seem a bit confusing :)

谢谢,
Michael

Thanks, Michael

推荐答案

with:


我需要没有编码的字节的确切值

I need the exact value of the bytes with no encoding

...


例如,如果字符串的值为(0xFF32)

For example if the value of the string is (0xFF32)

这有点像看油画,并说,我想要的图片的字节,没有编码。没有意义文本与二进制数据不同。一旦你明白了,很容易找到问题的根源。你真正想要的是作为一个字节数组的文件的内容。这很容易,因为文件是二进制数据!如果不是真正的文本,你不应该首先将其作为文本读取。幸运的是,.NET使它变得非常简单:

That's a bit like looking at an oil painting and saying, "I want the bytes for that picture, with no encoding." It doesn't make sense. Text isn't the same as binary data. Once you understand that, it's easy to get to the root of the problem. What you really want is the contents of a file as a byte array. That's easy, because files are binary data! You shouldn't be reading it as text in the first place if it isn't really text. Fortunately, .NET makes this really easy:

byte[] fileC = File.ReadAllBytes(dialog.FileName);

这篇关于C#将字符串转换成其byte []等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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