-1

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);    
    }                             
}
LipFong
  • 3
  • 4
  • Can you describe in what way you think your code is wrong? Is it not writing, or writing the incorrect output? Some other error? – Andrew Mortimer Nov 14 '16 at 08:17
  • 1
    Your code won't compile. You have to use the hexadecimal value prefix. – dymanoid Nov 14 '16 at 08:21
  • Where does `listC` come from? It mysteriously appears in the `foreach` loop... Also, isn't your list of `int` really a list of `byte`? – Matthew Watson Nov 14 '16 at 08:55
  • 1
    `string i in listC` - don't you mean `int i in list` ? – cbr Nov 14 '16 at 09:36
  • dymanoid, Matthew Watson and Cubrr, yes i cut part of my code out into this question, and something is missing/wrongly declared. i edited the questions and now it is compile-able. the solution that match my need is listed by haindl below. Thanks everyone. – LipFong Nov 15 '16 at 08:54

1 Answers1

0

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);
haindl
  • 3,111
  • 2
  • 25
  • 31
  • Your solution helped in my case. But i have million of data which converted from int to hex. Now i need to figure out how to convert my list to this byte with prefix. Thanks! – LipFong Nov 15 '16 at 02:45
  • @LipFong You're welcome! If you have another problem for which you can't find a solution here (or in your favorite search engine) then you can just ask another question. – haindl Nov 15 '16 at 06:47
  • @LipFong I've now seen your last edit. Just as an additional hint - if you have a list of strings and want to convert them into bytes, you can just do the following: `var list = new List { "1A" }.Select(s => byte.Parse(s, NumberStyles.HexNumber)).ToArray();` – haindl Nov 15 '16 at 12:55