简体   繁体   中英

How to convert byte array to binary values and then write it in a comma separated text file

I have a byte array:

newMsg.DATA = new byte[64];

How can I convert it into binary value and then write it in text file with comma separation. Comma should be in between binary values not bytes.....

like 1,1,1,0,0,0,1,1,1,1,1,0,0,0,0,0.......

Here is an example that uses LINQ:

byte[] arr = new byte[] { 11, 55, 255, 188, 99, 22, 31, 43, 25, 122 };

string[] result = arr.Select(x => string.Join(",", Convert.ToString(x, 2)
                     .PadLeft(8, '0').ToCharArray())).ToArray();

System.IO.File.WriteAllLines(@"D:\myFile.txt", result);

Every number in byte[] arr is converted to a binary number with Convert.ToString(x, 2) and the comma "," is added between binary values with string.Join(",",...) . At the end you can write all the elements in result to a text file by using System.IO.File.WriteAllLines .

The example above gives you this kind of output in a txt file:

0,0,0,0,1,0,1,1
0,0,1,1,0,1,1,1
1,1,1,1,1,1,1,1
...

Explanation of Convert.ToString(value, baseValue) :

The first parameter value represents the number you want to convert to a string and the second parameter baseValue represents which type of conversion you want to perform.

Posible baseValues are : 2,8,10 and 16.

BaseValue = 2 - represents a conversion to a binary number representation.

BaseValue = 8 - represents a conversion to a octal number representation.

BaseValue = 10 - represents a conversion to a decimal number representation.

BaseValue = 16 - represents a conversion to a hexadecimal number representation.

I think this will Help you c# provides inbuilt functionality to do so

with help of Convert.ToString(byte[],base); here base could be[2(binary),8(octal),16(HexaDecimal)]

        byte[] data = new byte[64];
        // 2nd parameter 2 is Base e.g.(binary)
        string a = Convert.ToString(data[data.Length], 2);
        StringBuilder sb = new StringBuilder();
        foreach(char ch in a.ToCharArray())
        {
            sb.Append(ch+",");
        }
        // This is to remove last extra ,
        string ans = sb.ToString().Remove(sb.Length - 1, 1);

This should get you going:

var bytes = new byte[] { 128, 255, 2 };
var stringBuilder = new StringBuilder();
for (var index = 0; index < bytes.Length; index++)
{
    var binary = Convert.ToString(bytes[index], 2).PadLeft(8, '0');
    var str = string.Join(",", binary.ToCharArray());
    stringBuilder.Append(str);
    if (index != bytes.Length -1) stringBuilder.Append(",");
}
Console.WriteLine(stringBuilder);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM