How can I convert bits to bytes?

The code is treating the first bit as the low bit of the word, so you end up with each word reversed. As a quick-and-dirty fix, try this:

bytes[byteIndex] |= (byte)(1 << (7-bitIndex));

That puts the first bit in the array at the highest position in the first byte, etc.


bool[] bools = ...
BitArray a = new BitArray(bools);
byte[] bytes = new byte[a.Length / 8];
a.CopyTo(bytes, 0);

EDIT: Actually this also returns:

198 12 209 77 203 162 216 50 33 0 196 255 194 231 125 159

Wrong endianness? I'll leave answer anyway, for reference.


EDIT: You can use BitArray.CopyTo() by reversing the arrays like so:

bool[] bools = ...
Array.Reverse(bools); // NOTE: this modifies your original array
BitArray a = new BitArray(bools);
byte[] bytes = new byte[a.Length / 8];
a.CopyTo(bytes, 0);
Array.Reverse(bytes);

I don't know if there's an automatic way to do it, but you can do it with a simple algorithm.

Simple algorithm:

  1. Create an array of bytes that will be used as your output buffer, and initialize all bytes to 0. The size of this array should be based on the length of your input boolean array: ceil(bool_array_length / 8.0)

  2. Declare an index variable to be used as your current byte, and set it to 0. This holds the index in your output buffer.

  3. Iterate over each element in your input boolean array. 3.1. Left bit shift the number 1 by the array index mod 8. Call this number your mask. 3.2. Calculate your byte index as your current index into the array div 8. 3.3. If you have a boolean true value the current index in your input boolean array, do a bitwise OR with your current byte and your mask.


Try this function (written as an extension method).

public byte[] ToByteArray(this bool[] bits)
{
    var bytes = new byte[bits.Length / 8];
    for (int i = 0, j = 0; j < bits.Length; i++, j += 8)
    {
        // Create byte from bits where LSB is read first.
        for (int offset = 0; offset < 8; offset++)
            bytes[i] |= (bits[j + offset] << offset);
    }

    return bytes;
}

Note: It will fail if the number of bits (bools) is not a multiple of 8, but judging by your question this isn't the case. It would only take a very small modificaiton to permit bit arrays of any length.


private static byte[] GetBytes(string bitString)
{
    byte[] result = Enumerable.Range(0, bitString.Length / 8).
        Select(pos => Convert.ToByte(
            bitString.Substring(pos * 8, 8),
            2)
        ).ToArray();

    List<byte> mahByteArray = new List<byte>();
    for (int i = result.Length - 1; i >= 0; i--)
    {
        mahByteArray.Add(result[i]);
    }

    return mahByteArray.ToArray();
}

private static String ToBitString(BitArray bits)
{
    var sb = new StringBuilder();

    for (int i = bits.Count - 1; i >= 0; i--)
    {
        char c = bits[i] ? '1' : '0';
        sb.Append(c);
    }

    return sb.ToString();
}

Comments

  1. Bradley

    • 2020/9/27

    How many Bytes in a Bit 1 Bit is equal to (1/8) × 100-0 Bytes. 1 Bit = (1/8) × 100 Bytes. 1 Bit = (1/8) × 1 Bytes. 1 b = 0.125 B. There are 0.125 Bytes in a 

  2. Pablo

    • 2017/9/9

    I don't know if there's an automatic way to do it, but you can do it with a simple algorithm. Simple algorithm: Create an array of bytes that will be used as your output buffer, and initialize all bytes to 0.

  3. Rizzo

    • 2015/3/3

    Bits to Bytes. Convert between the units (bit → B) or see the conversion table.

  4. Harvey

    • 2017/1/19

    1 bit = 1000 0 bits 1 bit = 1 × (1/8) bytes 1 bit = 0.125 bytes Bytes Byte is the basic unit of digital information transmission and storage, used extensively in information technology, digital technology, and other related fields.

  5. Phillips

    • 2015/5/21

    Basically, to do a bit to byte conversion, you take an 8 bit binary number and form it into groups of 4 bits (nibbles). You then translate each nibble into a 

  6. Canaan

    • 2015/8/30

    Basically, to do a bit to byte conversion, you take an 8 bit binary number and form it into groups of 4 bits (nibbles). You then translate each nibble into a hexadecimal number (a 2 hex digit byte) using this table. You then multiply the left digit by 16 and add the result to the first digit.

  7. Mitchell

    • 2018/1/13

    bits to Bytes Conversion Chart · 1 bits, 0.125 Bytes · 2 bits, 0.25 Bytes · 3 bits, 0.375 Bytes · 4 bits, 0.5 Bytes · 5 bits, 0.625 Bytes · 6 bits, 0.75 Bytes · 7 bits 

  8. Vincenzo

    • 2015/5/24

    1 Bits = 0.125 Bytes: 10 Bits = 1.25 Bytes: 2500 Bits = 312.5 Bytes: 2 Bits = 0.25 Bytes: 20 Bits = 2.5 Bytes: 5000 Bits = 625 Bytes: 3 Bits = 0.375 Bytes: 30 Bits = 3.75 Bytes: 10000 Bits = 1250 Bytes

  9. Emmitt

    • 2020/8/7

    To convert from bits to bytes, simply divide the number of bits by 8. For example, 256 bits are equal to 256 / 8 = 32 bytes. You can see more example 

  10. Orlando

    • 2018/8/12

    To convert from bits to bytes, simply divide the number of bits by 8. For example, 256 bits are equal to 256 / 8 = 32 bytes. You can see more example calculations and a conversion table below.

  11. Emmett

    • 2020/3/18

    The Digital Dutch Unit Converter - Online conversion of area, currency, density, energy, force, length, mass, power, pressure, Convert Bits & Bytes.

  12. Vincenzo

    • 2017/8/5

    Anything less than 8 bits is not a byte by my understanding. But you can't record 7 bits in 0 bytes. You would have to use one byte, but only partially occupied. Similarly I think 15 bits would require two bytes, again one only partially occupied. Careful; OP is having enough difficulty dividing by 8 at the best of times.

  13. Dariel

    • 2020/2/1

    Bit Calculator - Convert between bits/bytes/kilobits/kilobytes/megabits/megabytes/gigabits/gigabytes. Enter a number and choose the type of Units. Amount: Units 

  14. Jacoby

    • 2020/6/13

    For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111". A byte value IS integral, you can check bit state using masking operations.

  15. Carter

    • 2017/11/3

    A byte is made up of eight bits, or in other words, one bit is equal to 0.125 bytes and file size as you know is the measurement of how much material a file or 

  16. Cason

    • 2015/1/6

    1 byte = 8 bits · 1 kilobyte (K / Kb) = 2^10 bytes = 1,024 bytes · 1 megabyte (M / MB) = 2^20 bytes = 1,048,576 bytes · 1 gigabyte (G / GB) = 2^30 bytes = 

Comments are closed.

Recent Posts