Search code examples
c#hexbinarywriter

Write binary/hexadecimal value into .bin file from list of string/int


I want to write a long list of binary number into a binary file from a list. The list are now all Hexadecimal number. My code below is not giving what i want like case 1, instead it output case 2. Please help.

Case 1: What i need is a binary file - 1A0F83.....

Case 2: but not - 314130463833.....

List<string> list = new List<string>(new string[]{"1A", "0F", "83" }); 

using (var s = File.Open("test.bin", FileMode.Create))
{
    var tw = new BinaryWriter(s);                

    foreach (string i in list) // Loop through all strings
    {               
        tw.Write(i);    
    }                             
}

Solution

  • If you want to write a sequence of single bytes to a binary file then just write a single byte at a time (not an int which is 4 bytes in size) and change the following line

    tw.Write(i);
    

    to this:

    tw.Write((byte)i);
    

    Or if you want to clean up your code a little bit, increase the performance for longer sequences and make it compilable too, you can just use this:

    var list = new List<byte> { 0x1A, 0x0F, 0x83 }.ToArray();
    
    using (var s = File.Open("test.bin", FileMode.Create))
    using (var tw = new BinaryWriter(s))
        tw.Write(list);