简体   繁体   中英

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? 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.

Thanks a lot!

with string.Split , Convert.ToByte , and FileStream or File.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

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array.

Convert.ToByte Method (String, Int32)

Converts the string representation of a number in a specified base to an equivalent 8-bit unsigned integer.

FileStream Class

Provides a Stream for a file, supporting both synchronous and asynchronous read and write operations.

File.WriteAllBytes Method (String, Byte[])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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