Search code examples
c#type-conversionuint32uint16

Convert two UInt16 Values to one UInt32 Value consider least and most significant word


I have two UInt16 values

private UInt16 leastSignificantWord;
private UInt16 mostSignificantWord;

The two words (UInt16 values) come from a component which divides a UInt32 status / error value into two words and returns the two words. Now i need get back to the UInt32 value. To sum the two words together wouldn't do the trick because of disregard if the most and least significant.

For example:

 private UInt16 leastSignificantWord = 1;
 private UInt16 mostSignificantWord = 1;

//result contains the value 2 after sum both words
//which can not be correct because we have to take note of the most and least significant
UInt32 result = leastSignificantWord  + mostSignificantWord;

Is there a way to solve this? To be honest i have never worked with bits / bytes in c# so i had never faced such a problem. Thanks in advance


Solution

  • private UInt16 leastSignificantWord = 1;
    private UInt16 mostSignificantWord = 1;
    
    UInt32 result = (leastSignificantWord << 16) + mostSignificantWord;
    

    You have 2 UInt16 (16 bit and 16 bit) one 0010 1011 1010 1110 and second 1001 0111 0100 0110

    If you will read this 2 UIn16 as one UInt32 you will have 0010 1011 1010 1110 1001 0111 0100 0110

    So, (leastSignificantWord << 16) gives you 0010 1011 1010 1110 0000 0000 0000 0000 and this plus mostSignificantWord gives you 0010 1011 1010 1110 1001 0111 0100 0110

    These can be helpful

    http://msdn.microsoft.com/en-us/library/a1sway8w.aspx

    What are bitwise shift (bit-shift) operators and how do they work?