|
-
Nov 3rd, 2009, 10:16 AM
#1
Thread Starter
Hyperactive Member
Hex / Binary
Code:
byte[] buff = new byte[4];
buff[0] = 0x34;
buff[1] = 0x23;
buff[2] = 0x00;
buff[3] = 0xF2;
FileStream fs = new FileStream("hex.bin", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff);
bw.Close();
Console.WriteLine("Written to file : hex.bin");
Right. That writes (34 23 00 F2) to a file in binary (specifically NOT text).
I would like to read a hex number (lets just say 342300F2) from a text file and encode that same hex number to a binary file. I cant work out how to process the text into binaray. Any ideas?
Last edited by francisstokes; Nov 3rd, 2009 at 10:23 AM.
-
Nov 3rd, 2009, 05:19 PM
#2
Re: Hex / Binary
Something like this?
csharp Code:
public void ProcessHex() { string yourHex = "342300F2"; string binary = string.Empty; if (!yourHex.TryBinaryParse(ref binary)) { Console.WriteLine("Invalid hex format"); } else { Console.WriteLine(binary); } }
csharp Code:
public static class Extensions { public static bool TryBinaryParse(this string hexInput, ref string result) { try { if (!System.Text.RegularExpressions.Regex.Match(hexInput, "^[A-Fa-f0-9]+$").Success) { return false; } hexInput = hexInput.ToUpper(); Dictionary<char, string> lookup = new Dictionary<char, string>(16); { lookup.Add('0', "0000"); lookup.Add('1', "0001"); lookup.Add('2', "0010"); lookup.Add('3', "0011"); lookup.Add('4', "0100"); lookup.Add('5', "0101"); lookup.Add('6', "0110"); lookup.Add('7', "0111"); lookup.Add('8', "1000"); lookup.Add('9', "1001"); lookup.Add('A', "1010"); lookup.Add('B', "1011"); lookup.Add('C', "1100"); lookup.Add('D', "1101"); lookup.Add('E', "1110"); lookup.Add('F', "1111"); } result = string.Join(string.Empty, hexInput.ToCharArray().Select((c) => lookup[c]).ToArray()); return true; } catch { return false; } } }
I thought it might be cool as an extension.
-
Nov 4th, 2009, 02:59 AM
#3
Thread Starter
Hyperactive Member
Re: Hex / Binary
Ok i dont think ive been clear. What im looking for is if i were to open a file in a hex editor, i would see this:
Code:
00000: 34 23 00 F2 xx xx xx xx ..... ...B.
I want to take text versions of those hex symbols [34, 23, 00, F2] and encode them in hex. If i were encoding in text the file would look like this:
Code:
00000: 33 34 32 33 30 30 46 32 34230 0F2..
I hope that clears things up.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|