C#, bits & bytes - How do I retrieve bit values from a byte?

前端 未结 5 1031
陌清茗
陌清茗 2020-12-29 08:04

I\'m reading some values from a single byte. I\'m told in the user-manual that this one byte contains 3 different values. There\'s a table that looks like this:

5条回答
  •  借酒劲吻你
    2020-12-29 08:37

    You can do shifts and masks, or you can use the BitArray class: http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx

    Example with BitVector32:

    BitVector32 bv = new BitVector32(0);
    
    var size = BitVector32.CreateSection(7);
    var scale = BitVector32.CreateSection(3, size);
    var precision = BitVector32.CreateSection(7, scale);
    
    bv[size] = 5;
    bv[scale] = 2;
    bv[precision] = 4;
    

    LINQPad output:

    LINQPad output

提交回复
热议问题