Set a specific bit in an int

Michael Kingsmill

I need to mask certain string values read from a database by setting a specific bit in an int value for each possible database value. For example, if the database returns the string "value1" then the bit in position 0 will need to be set to 1, but if the database returns "value2" then the bit in position 1 will need to be set to 1 instead.

How can I ensure each bit of an int is set to 0 originally and then turn on just the specified bit?

user2819245

If you have an int value "intValue" and you want to set a specific bit at position "bitPosition", do something like:

intValue = intValue | (1 << bitPosition);

or shorter:

intValue |= 1 << bitPosition;


If you want to reset a bit (i.e, set it to zero), you can do this:

intValue &= ~(1 << bitPosition);

(The operator ~ reverses each bit in a value, thus ~(1 << bitPosition) will result in an int where every bit is 1 except the bit at the given bitPosition.)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Set Specific Bit in Byte Array

From Dev

Hexadecimal: Set an 8-bit byte in an int

From Dev

Get last set bit position for an int

From Dev

Check whether a specific bit is set in Python 3

From Dev

Manually set NX bit of specific PTE

From Dev

VHDL Is there a cleaner way to set specific bit, given the bit number?

From Dev

VHDL Is there a cleaner way to set specific bit, given the bit number?

From Dev

how to access a specific bit in an int variable in x86 assembly to check if it is 0 or 1?

From Dev

C set a bit (bit manipulation)

From Dev

Convert INT to BIT

From Dev

java micro-optimization: combine set of boolean instance variables to bit vector based on int

From Dev

Can we set an array of 32 bit int as a key's value in Redis as binary data in node.js?

From Dev

How to set, clear a bit of a long long int number in C/C++?

From Dev

Removing bit at specific index

From Dev

Modify specific bit in byte

From Dev

How to set the superuser bit?

From Dev

Prolog: testing if bit is set

From Dev

How to set the bit in position?

From Dev

Checking if bit is not set

From Dev

How to set the superuser bit?

From Dev

Bit twiddling to get sign bit of 32 bit int

From Dev

PHP pack 9 bit int then 10 bit int

From Dev

numpy parse int into bit groupings

From Dev

bit representation of unsigned int a = -1

From Dev

Setting nth bit of unsigned int

From Dev

Put bit int value into bitarray

From Dev

Generating specific bit sequences in Python

From Dev

Bit Field of a specific size and order

From Dev

How to render in a specific bit depth?