Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set and Unset a specific bit in a 64-bit integer

OK, what I want is pretty straight forward :

  • Set Nth bit of a number (= make it '1')
  • Unset Nth bit of a number (= make it '0')

This is my code so far (in the form of 2 macros) :

#define SETBIT(X,Y)     X|=(1ULL<<(Y))
#define UNSETBIT(X,Y)   X&=(~(1ULL<<(Y)))

They are both working fine. The thing is :

  • Is there anything that could be optimized?
  • Could it be made even faster?

(Both operations are supposed to be performed some millions of times per second, so performance is more than crucial).

like image 811
Dr.Kameleon Avatar asked Dec 11 '22 19:12

Dr.Kameleon


2 Answers

You can marginally speed up compilation time by getting rid of the macros, but that's about it. Bit twiddling is fast enough so it shouldn't be an issue.

This is the idiomatic way of doing it, I wouldn't change a thing.

like image 176
Luchian Grigore Avatar answered Dec 28 '22 01:12

Luchian Grigore


This is the standard way of setting and clearing a bit in C.

If you want to potentially speed up these macros you can have a look at Linux assembly implementations of these operations.

For example, for x86:

http://lxr.linux.no/linux/arch/x86/include/asm/bitops.h

Look for __clear_bit and __set_bit inline functions.

like image 28
ouah Avatar answered Dec 28 '22 01:12

ouah