2

I have a byte array of 48 bytes and would like to read every third bit of a byte in this array, how can i achieve this?

this is the output of my device

100510000 10000000 100390000 10000000 100390000 10000000 100460000 10000000 100390000 10000000 100390000 10000000 100390000 10000000 100390000 10000000 100390000 10000000 100320000 10000000 100460000 10000000 100390000 10000000 100390000 10000000 100320000 10000000 100460000 10000000 100390000 10000000 100300000 10000000 100300000 10000000 100310000 10000000 100310000 10000000 100390000 10000000 100300000 10000000 100320000 10000000 120560000 10000000

4

6 回答 6

1
byte[] bytes;
for (var i = 0; i < bytes.Length; i++)
{
   BitArray bits=    bytes[i];
   bool bit3= bits[2];
}
于 2013-04-22T13:51:07.987 回答
1

尝试这个:

byte[] bytearray = new byte[4];

var result = bytearray.Select(input=>new System.Collections.BitArray(input)[2]);
于 2013-04-22T13:52:27.583 回答
1

这将迭代所有字节并返回一个字节中的指定位。

    byte[] myBytes;         // populate here
    int bitLocation = 2;    // Bit number
    for (var i = 0; i < myBytes.Length; i++)
    {
        byte myByte = myBytes[i];
        var requiredBit = Convert.ToInt32((myByte & (1 << bitLocation - 1)) != 0);
        // save the requiredBit somehow
    }
于 2013-04-22T14:03:33.787 回答
1
byte[] bytes;
for (var i = 0; i < bytes.Length; i++)
{
    bytes[i] &= 4;
}
于 2013-04-22T13:48:10.570 回答
1

(假设您希望输出为与字节中的位相对应的 1 位和 0 位的流,将所有字节中的所有位视为一个长的位流。)

你可以这样做:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = new byte[] { 0xff, 0x00, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, };

            foreach (var b in BitReader(bytes, 3))
            {
                Console.WriteLine(b);
            }
        }

        public static IEnumerable<byte> BitReader(IEnumerable<byte> bytes, int stride)
        {
            int bit = 0;

            foreach (var b in bytes)
            {
                while (true)
                {
                    yield return (byte)(((b & (1 << bit)) != 0) ? 1 : 0);

                    bit += stride;

                    if (bit > 7)
                    {
                        bit %= 8;
                        break;
                    }
                }
            }
        }
    }
}
于 2013-04-22T14:06:34.197 回答
1
private bool BitCheck(byte b, int pos)
{
    return (b & (1 << (pos-1))) > 0;
}
于 2013-04-22T13:49:56.510 回答