当前位置: 动力学知识库 > 问答 > 编程问答 >

Check if uint16_t contains binary uin8_t

问题描述:

Suppose I have two bytes, 0xE1 and 0xE6. These consecutive bytes where cut from a longer range of bits. Since the cutting point is not related to the actual byte values, I need to check whether these bytes contain another, say 0x3C. Basically a binary string contains.

0xE1 0xE6

1110000111100110

00111100 // It matches!

0x3C

How do I algorithmically test this?

网友答案:

Shift the word (2 bytes) to the right, get the lower byte and compare !

Play with it here

#include <stdio.h>

int contains(short twobytes, char onebyte)
{
    int i=0;
    for (; i<8; i++)
    {
        if (onebyte == ((twobytes >> i) & 0xFF))
          return 1;
    }
    return 0;
}

int main(void) {
    if (contains(0xE1E6, 0x3C))
    {
        printf("YES!\n");
    }
    else
    {
        printf("No :(\n");
    }
    return 0;
}
网友答案:

It's a binary string... so any string search should work. For example this simple C# snippet should work:

ushort s = 123;
byte b = 3;
//0000000001111011
string sBitString = Convert.ToString(s, 2).PadLeft(16,'0');
//00000011
string bBitString = Convert.ToString(b, 2).PadLeft(8,'0');
//True, because the strings match at zero-based index 3 
bool result = sBitString.Contains(bBitString);

Of course, this particular implementation isn't the most performant - it'd be possible to write a more efficient solution with knowledge of bitwise operators - but as always this is dependant on your performance needs.

static void Main(string[] args)
{
    ushort s = 123;
    byte b = 3;
    int result = IndexOf(s, b);

    Console.ReadLine();
}

static int IndexOf(ushort s, byte b)
{
    for (int i = 0; i < 8; i++)
    {
        //  First we shift the short down into a byte: (s >> (8 - i))
        //  This removes the 'right' bits.  We then do an 'and'  
        //  to remove any unnecessary 'left' bits.
        var shortSegment = (s >> (8 - i)) & 255;
        if (shortSegment == b) return i;
    }
    return -1;
}

(Note: ushort represents two bytes in C#, while a byte represents 1 byte).

分享给朋友:
您可能感兴趣的文章:
随机阅读: