开发者

To read the hex value of a .txt file in c#

开发者 https://www.devze.com 2023-03-20 19:35 出处:网络
If I have some text file like abc.txt the I want to the hex value of that .txt file like we see when we open notepad+ can click on hex...something like this

If I have some text file like abc.txt the I want to the hex value of that .txt file like we see when we open notepad+ can click on hex...something like this

74 68 65 72 77 69 73 65 20 69 7开发者_运维技巧3 20 69 74 63 68    
therwise is itch

69 6e 27 20 66 6f 72 20 61 20 66 69 67 68 74 2e     
in' for a fight.

Now i want these hex values of individual letters.

I know how to read text by using FileStream() and StreamReader().

But now want these hex values how can i get this?


BinaryReader reader = new BinaryReader(new FileStream("C:\\file.ext", FileMode.Open, FileAccess.Read, FileShare.None));
reader.BaseStream.Position = 0x0;     // The offset you are reading the data from
byte[] data = reader.ReadBytes(0x10); // Read 16 bytes into an array
reader.Close();

So assuming the input is therwise is itch:

string data_as_str = Encoding.Default.GetString(data); // Output: therwise is itch
string data_as_hex = BitConverter.ToString(data);      // Output: 74-68-65-72-77-69-73-65-20-69-73-20-69-74-63-68


Open using FileStream, then use Read to get arrays of byte. For each element in the array convert to a hex pair with byteVal.ToString("x2") (use X2 if you want uppercase hex).

0

精彩评论

暂无评论...
验证码 换一张
取 消