VB.NET Bit manipulation: how to extract byte from short?

孤街醉人 提交于 2019-12-13 02:14:50

问题


Given this Short (signed):

&Hxxxx

I want to:

  • Extract the most right &HxxFF as SByte (signed)
  • Extract the left &H7Fxx as Byte (unsigned)
  • Identify if the most left &H8xxx is positive or negative (bool result)

回答1:


Uh...

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

EDIT: I suppose you want the byte value and not just the upper 8 bits.




回答2:


Extract the most right 0xxxff

myShort & 0x00FF

Extract the left 0xffxx

(myShort & 0xFF00) >> 8

Identify if the most left 0xfxxx is positive or negative (it's a signed short).

(myShort & 0xF000) >= 0;



回答3:


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



回答4:


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;
}



回答5:


  • Extract the most right &HxxFF as SByte (signed)

    CType(s AND &H00FF, SByte)

  • Extract the left &H7Fxx as Byte (unsigned)

    CType((s AND &H7F00) >> 8, Byte)

  • Identify if the most left &H8xxx is positive or negative (bool result)

    s AND &H8000 > 0

I think those work, been a while since I have worked in VB



来源:https://stackoverflow.com/questions/3199576/vb-net-bit-manipulation-how-to-extract-byte-from-short

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!