Shifting number with position and value (C#)

December 30, 2014 at 10:17 (.Net) ()

        static void Main(string[] args)
        {
            /** Chapter 3 Example 13 (no user input) **/
            byte aByte = 35;
            int p = 2;
            int v = 1;

            if (v == 0)
            {
                Set(ref aByte, p, false);
            }
            else if (v == 1)
            {
                Set(ref aByte, p, true);
            }

            Console.WriteLine(aByte);
        }

        public static void Set(ref byte aByte, int pos, bool value)
        {
            if (value)
            {
                //left-shift 1, then bitwise OR
                aByte = (byte)(aByte | (1 << pos));
            }
            else
            {
                //left-shift 1, then take complement, then bitwise AND
                aByte = (byte)(aByte & ~(1 << pos));
            }
        }

        public static bool Get(byte aByte, int pos)
        {
            //left-shift 1, then bitwise AND, then check for non-zero
            return ((aByte & (1 << pos)) != 0);
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s