简体   繁体   English

C#-写入包含十六进制值作为字节的字符串

[英]c# - write string that contains hex values as bytes

let's say I have a string 假设我有一个字符串

string hex = "55 6E 6B 6E 6F 77 6E 20 53 70 61 63 65"

I want to write these to a file but they should be the bytes itself. 我想将这些写入文件,但是它们应该是字节本身。 so the result would be Unknown Space. 因此结果将是“未知空间”。

Is there any way to do that directly instead of first encoding it to utf-8 and write that to the file? 有什么方法可以直接执行此操作,而不是先将其encodingutf-8并将其写入文件吗? the reason I'm asking is that sometimes there is the special character of utf-8 in the (like eg 0xE28780 ) which wouldn't work well if I first split the string into chars of each value. 我要问的原因是,有时(例如0xE28780 )中会有utf-8的特殊字符,如果我先将字符串分成每个值的chars,那将无法正常工作。

Thanks a lot! 非常感谢!

with string.Split , Convert.ToByte , and FileStream or File.WriteAllBytes string.SplitConvert.ToByteFileStreamFile.WriteAllBytes

string hex = "55 6E 6B 6E 6F 77 6E 20 53 70 61 63 65";
var bytes = hex.Split(' ')
               .Select(x => Convert.ToByte(x, 16))
               .ToArray();

using (var fs = new FileStream(@"D:\test2.dat",FileMode.Create))
   fs.Write(bytes,0,bytes.Length);

// or even easier 

File.WriteAllBytes(@"D:\test2.dat",bytes);

String.Split Method String.Split方法

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array. 返回一个字符串数组,其中包含此实例中的子字符串,这些子字符串由指定字符串或Unicode字符数组的元素定界。

Convert.ToByte Method (String, Int32) Convert.ToByte方法(字符串,Int32)

Converts the string representation of a number in a specified base to an equivalent 8-bit unsigned integer. 将指定基数中的数字的字符串表示形式转换为等效的8位无符号整数。

FileStream Class FileStream类

Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations. 提供文件流,支持同步和异步读取和写入操作。

File.WriteAllBytes Method (String, Byte[]) File.WriteAllBytes方法(字符串,字节[])

Creates a new file, writes the specified byte array to the file, and then closes the file. 创建一个新文件,将指定的字节数组写入该文件,然后关闭该文件。 If the target file already exists, it is overwritten. 如果目标文件已经存在,则将其覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM