James Cadd James Cadd - 1 year ago 104
C# Question

C# get and set the high order word of an integer

What's an efficient or syntactically simple way to get and set the high order part of an integer?

Answer Source

It's the same as in C/C++:

// get the high order 16 bits
int high = 0x12345678 >> 16; // high = 0x1234
// set the high order 16 bits
high = (high & 0x0000FFFF) + (0x5678 << 16); // high = 0x56781234

EDIT: Because I'm in a good mood, here you go. Just remember, immutable types are immutable! The 'set' functions need to be assigned to something.

public static class ExtensionMethods
    public int LowWord(this int number)
    { return number & 0x0000FFFF; }
    public int LowWord(this int number, int newValue)
    { return (number & 0xFFFF0000) + (newValue & 0x0000FFFF); }
    public int HighWord(this int number)
    { return number & 0xFFFF0000; }
    public int HighWord(this int number, int newValue)
    { return (number & 0x0000FFFF) + (newValue << 16); }

EDIT 2: On second thoughts, if you really need to do this and don't want the syntax everywhere, use Michael's solution. +1 to him for showing me something new.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download