Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit manipulation in C# using a mask

I need a little help with bitmap operations in C#

I want to take a UInt16, isolate an arbitrary number of bits, and set them using another UInt16 value.

Example:

10101010  -- Original Value
00001100  -- Mask - Isolates bits 2 and 3

Input        Output
00000000  -- 10100010
00000100  -- 10100110
00001000  -- 10101010
00001100  -- 10101110
                 ^^
like image 867
Robert Harvey Avatar asked Jul 12 '10 17:07

Robert Harvey


1 Answers

It seems like you want:

(orig & ~mask) | (input & mask)

The first half zeroes the bits of orig which are in mask. Then you do a bitwise OR against the bits from input that are in mask.

like image 69
JSBձոգչ Avatar answered Sep 30 '22 12:09

JSBձոգչ