Extract unsigned values from certain bits in C# ushort

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Johan Simpson
    New Member
    • Nov 2010
    • 2

    #1

    Extract unsigned values from certain bits in C# ushort

    Hi all.

    I need a good way of extracting values from certain bits inside a unsigned short:


    The definition of the 4 alarms inside the ushort:

    Name......Range .......Bits
    Alarm4....0-15....13/16-16/16
    Alarm3....0-15....9/16-12/16
    Alarm2....0-15....5/16-8/16
    Alarm1....0-15....1/16-4/16


    The value of the ushort: 4383 or (1000100011111 in binary)


    So what i want to achieve is:
    100110011001100 1
    Alarm1.....Alar m2.....Alarm3.. ....Alarm4
    1001.......1001 .......1001.... ....1001

    Gets translated into:
    Alarm1....Alarm 2....Alarm3.... Alarm4
    9............9. ...........9... .........9


    Using the pseudo code:
    Code:
     getValueFunc(ushort bits, int offset);
    
     ushort u = 4383;
     UInt16 Alarm1Value = getValueFunc(u, 1);
     UInt16 Alarm2Value = getValueFunc(u, 5);
     UInt16 Alarm3Value = getValueFunc(u, 9);
     UInt16 Alarm4Value = getValueFunc(u, 13);

    Thank you very much in advance for your time.

    Regards,
    Johan
  • Christian Binder
    Recognized Expert New Member
    • Jan 2008
    • 218

    #2
    Taking the second four bits:
    1001100110011001 if you & (and) it with
    000000001111000 0 you'll get
    000000001001000 0 when you shift this thing by four places,
    000000000000100 1 you'll get what you want

    this would look like
    Code:
    ushort getValueFunc(ushort bits, int offset) {
      //assume offset starts by zero (right four bytes)
      //bits:   1001 1001 1001 1001
      //offset:  3    2    1    0
      //result:  9    9    9    9
    
      ushort and_value = 15; // 1111
      and_value <<= offset * 4;
        //move it offset*4 binary places to the left
        //offset  and_value
            0                   1111
            1               11110000
            2           111100000000
            3       1111000000000000
    
    
      bits &= and_value; //and-ing
    
      bits >>= offset * 4:
      //move it back offset*4 binary places to the right
    
      return bits;
    }
    I hope this works and helps :-)

    Comment

    • Johan Simpson
      New Member
      • Nov 2010
      • 2

      #3
      Just tested it, works 100%.

      Thank you very much for the solution and explaination, now it makes sense for people like me with little binary experience :)

      Comment

      • Christian Binder
        Recognized Expert New Member
        • Jan 2008
        • 218

        #4
        Fine :-) you're welcome

        Comment

        Working...