【问题标题】:Set 3 bits in the middle of the byte C# (bitwise operators)在字节中间设置 3 位 C#(按位运算符)
【发布时间】:2021-05-08 17:03:54
【问题描述】:
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            byte value = 0;
            value = SetValue(value,5,3,7);
            Console.WriteLine("{0}", value);
        }
        public static byte Mask(int l, int p)
        {
            return Convert.ToByte(~(0xff << (l)) << (p));
        }

        public static byte GetValue(int bitfield, int l, int p)
        {
            return Convert.ToByte((((bitfield) & Mask(l, p)) >> p));
        }

        public static byte SetValue(int bitfield, int l, int p, int value)
        {
            return Convert.ToByte((bitfield) = ((bitfield) & ~Mask(l, p)) | (((value) << (p)) & Mask(l, p)));
        }
    }
}

我得到: 抛出异常:mscorlib.dll 中的“System.OverflowException” mscorlib.dll 中出现“System.OverflowException”类型的未处理异常 附加信息:对于无符号字节而言,值太大或太小。

我是 C# 新手,当我在 C 中使用非常相似的东西时效果很好..

【问题讨论】:

    标签: c# .net bit-manipulation operators bit


    【解决方案1】:
        public static byte Mask(int l, int p)
    {
        return Convert.ToByte(~(0xffffffff << (l)) << (p));
    }
    
    public static byte GetValue(int bitfield, int l, int p)
    {
        return Convert.ToByte((((bitfield) & Mask(l, p)) >> p));
    }
    
    public static byte SetValue(int bitfield, int l, int p, int value)
    {
        return Convert.ToByte((bitfield) =
                                  ((bitfield) & ~Mask(l, p)) |
                                  (((value) << (p)) & Mask(l, p)));
    }
    

    }

    C# 使用整数进行位操作,将 0xff 改为 0xffffffff

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      相关资源
      最近更新 更多