[C#]获取与设置Byte中的Bit值

这篇博客介绍了如何在C#中获取和设置字节中的特定位(Bit)值。提供了两个实用函数,一个用于获取指定索引Bit的值,另一个用于设置指定索引Bit的值。通过位运算实现,适用于二进制数据处理。

关键知识点:

  • 1Byte=8Bit;
  • Bit为二进制;

一.获取Byte里的指定Bit值的函数:

/// <summary>
/// 获取字节中的指定Bit的值
/// </summary>
/// <param name="this">字节</param>
/// <param name="index">Bit的索引值(0-7)</param>
/// <returns></returns>
public static int GetBit(this byte @this, short index)
{
    byte x = 1;
    switch (index)
    {
        case 0: { x = 0x01; } break;
        case 1: { x = 0x02; } break;
        case 2: { x = 0x04; } break;
        case 3: { x = 0x08; } break;
        case 4: { x = 0x10; } break;
        case 5: { x = 0x20; } break;
        case 6: { x = 0x40; } break;
        case 7: { x = 0x80; } break;
        default: { return 0; }
    }
    return (@this & x) == x ? 1 : 0;
}

二.设置Byte里的指定Bit值的函数:

/// <summary>
/// 设置字节中的指定Bit的值
/// </summary>
/// <param name="this">字节</param>
/// <param name="index">Bit的索引值(0-7)</param>
/// <param name="bitvalue">Bit值(0,1)</param>
/// <returns></returns>
public static byte SetBit(this byte @this, short index, int bitvalue)
{
    var _byte = @this;
    if (bitvalue == 1)
    {
        switch (index)
        {
            case 0: { return _byte |= 0x01; } 
            case 1: { return _byte |= 0x02; } 
            case 2: { return _byte |= 0x04; } 
            case 3: { return _byte |= 0x08; } 
            case 4: { return _byte |= 0x10; } 
            case 5: { return _byte |= 0x20; } 
            case 6: { return _byte |= 0x40; } 
            case 7: { return _byte |= 0x80; } 
            default: { return _byte; }
        }
    }
    else
    {
        switch (index)
        {
            case 0: { return _byte &= 0xFE; } 
            case 1: { return _byte &= 0xFD; } 
            case 2: { return _byte &= 0xFB; } 
            case 3: { return _byte &= 0xF7; } 
            case 4: { return _byte &= 0xEF; } 
            case 5: { return _byte &= 0xDF; } 
            case 6: { return _byte &= 0xBF; } 
            case 7: { return _byte &= 0x7F; } 
            default: { return _byte; }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值