c# - write string that contains hex values as bytes
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 e.g. 0xE28780) which wouldn't work well if I first split the string into chars of each value.
encoding
utf-8
utf-8
0xE28780
Thanks a lot!
1 Answer
1
with string.Split, Convert.ToByte, and FileStream or File.WriteAllBytes
string.Split
Convert.ToByte
FileStream
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.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
thanks a lot! worked perfectly
– Ginsor
Jun 30 at 10:56