如何读取字节数组中的每第三位

时间:2013-04-22 13:45:20

标签: c# buffer byte

我有一个48字节的字节数组,想读取这个数组中每个字节的第三位,我该怎么做呢?

这是我设备的输出

  

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

6 个答案:

答案 0 :(得分:1)

byte[] bytes;
for (var i = 0; i < bytes.Length; i++)
{
    bytes[i] &= 4;
}

答案 1 :(得分:1)

private bool BitCheck(byte b, int pos)
{
    return (b & (1 << (pos-1))) > 0;
}

答案 2 :(得分:1)

byte[] bytes;
for (var i = 0; i < bytes.Length; i++)
{
   BitArray bits=    bytes[i];
   bool bit3= bits[2];
}

答案 3 :(得分:1)

试试这个:

byte[] bytearray = new byte[4];

var result = bytearray.Select(input=>new System.Collections.BitArray(input)[2]);

答案 4 :(得分: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
    }

答案 5 :(得分: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;
                    }
                }
            }
        }
    }
}
相关问题