【问题标题】:VB.NET Bit manipulation: how to extract byte from short?VB.NET 位操作:如何从短中提取字节?
【发布时间】:2018-05-11 07:57:16
【问题描述】:

鉴于此短片(签名):

&Hxxxx

我想:

  • 将最右边的&HxxFF提取为SByte(签名)
  • 将左边的&H7Fxx提取为字节(无符号)
  • 确定最左边的&H8xxx 是正数还是负数(布尔结果)

【问题讨论】:

  • 最 sig 位是 0x8000 而不是 0xf000 btw。
  • 对。问题已更新。

标签: vb.net bit-manipulation math short


【解决方案1】:

提取最右边的0xxxff

myShort & 0x00FF

提取左边的0xffxx

(myShort & 0xFF00) >> 8

判断最左边的 0xfxxx 是否为 正面或负面(这是一个有符号的 短)。

(myShort & 0xF000) >= 0;

【讨论】:

    【解决方案2】:
    Dim test As UInt16 = &HD 'a test value 1101
    Dim rb As Byte 'lsb
    Dim lb As Byte 'msb - 7 bits
    Dim rm As UInt16 = &HFF 'lsb mask
    Dim lm As UInt16 = &H7F00   'msb mask
    Dim sgn As Byte = &H80 'sign mask
    
    For x As Integer = 0 To 15 'shift the test value one bit at a time
        rb = CByte(test And rm) 'get lsb
        lb = CByte((test And lm) >> 8) 'get msb
        Dim lbS, rbS As Boolean 'sign
    
        'set signs
        If (rb And sgn) = sgn Then rbS = True _
         Else rbS = False
    
        If (lb And sgn) = sgn Then lbS = True _
         Else lbS = False 'should always be false based on mask
    
        Console.WriteLine(String.Format("{0} {1} {2}  {3} {4}",
            x.ToString.PadLeft(2, " "c),
            Convert.ToString(lb, 2).PadLeft(8, "0"c),
            Convert.ToString(rb, 2).PadLeft(8, "0"c),
            lbS.ToString, rbS.ToString))
    
        test = test << 1
    Next
    

    【讨论】:

    • @Shimmy - 表单应用程序中的控制台?这就是我使用 Debug 的原因,不管是表单还是控制台。
    • 没关系,如果您注意到这也是我编辑的原因,我还将代码格式化为适合 vb 10
    【解决方案3】:
    inline char getLsb(short s)
    {
        return s & 0xff;
    }
    
    inline char getMsb(short s)
    {
        return (s & 0xff00) >> 8; 
    }
    
    inline bool isBitSet(short s, unsigned pos)
    {
        return (s & (1 << pos)) > 0;
    }
    

    【讨论】:

      【解决方案4】:

      呃……

      value & 0x00ff
      (value & 0xff00) >> 8
      (value & 0xf000) >= 0
      

      编辑:我想你想要字节值而不仅仅是高 8 位。

      【讨论】:

        【解决方案5】:
        • 提取最右边的 &HxxFF 为 SByte (signed)

          CType(s AND &amp;H00FF, SByte)

        • 将左边的 &H7Fxx 提取为字节(无符号)

          CType((s AND &amp;H7F00) &gt;&gt; 8, Byte)

        • 判断最左边的&H8xxx是正还是负(bool结果)

          s AND &amp;H8000 &gt; 0

        我认为这些工作,自从我在 VB 工作以来已经有一段时间了

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-02
          • 2019-12-13
          • 1970-01-01
          • 2012-05-20
          相关资源
          最近更新 更多