Sie sind auf Seite 1von 6

Search

Home

QUEST ION T OPI CS

Bitwise Programming

Open Questions

Computer Programming: What are some cool bit


manipulation tricks/hacks?
This is a followup question to Python (programming language): What are some
cool Python tricks? and Ruby (programming language): What are some cool
Ruby tricks?

Boolean Logic
Tips and Hacks
Hacking (computing)

Follow Question 291

Comment Share 9

Notifications

Downvote

Learning to Program

Nalan

Add Question

REL A T ED QUEST I ONS

C (programming language): Are there any


good bit manipulation tutorials for C/C++?
Competitive Programming: What are
some interesting examples of bit
manipulation usage in competitive
programming?
Python (programming language): What

Computer Science

are some cool Python tricks?

Nalan KR

Computer Programming

Edit Bio Make Anonymous

Python (programming language): How


would you add two integers using bit
manipulation?

Edit Topics

Add your answer, or answer later.


SHA RE QUEST ION
32 ANSWERS

A SK T O A NSWER

Ruby (programming language): What are


some cool Ruby tricks?

Twitter

Utkarsh Shahdeo, BIT Mesra, CSE Undergrad

Facebook

60 upvotes by Pavan Vamsi, Vlad-Doru Ion, Yogiraj Banerji, (more)

Code to find the Greatest Common Divisor of two numbers.


QUEST ION ST AT S

1 int GCD(int a,int b)


2 {

Views

17,804

while(b^=a^=b^=a%=b);

return a;

Aliases
Followers

291

Data Structures: What are some cool


things one can do with sets?
Quora (product): What are some really
cool Quora hacks?
CMD: What are some cool hacking tricks
using cmd.exe?

5 }

What cool things can one do with an

iPhone and iPad that most people don't


know about?

Written 16 Jun.
Upvote 60

Downvote Comment Share


MATLAB: What are some cool MATLAB
tricks?

Latest activity: 11 Jul

Laukik Nirgudkar
43 upvotes by Vikrant Singh, Tapasweni Pathak, Himani Garg, (more)

The one we used in many time pad.


"CAPITAL LETTER" XOR " " = "small letter"
"W" XOR " " = "w"
"g" XOR " " = "G"
Written 9 Jun.
Upvote 43

Downvote Comment 1

Share

Yoshiya Miyata, Software Engineer at Google


97 upvotes by Sumeet Jain, Naveen Jain, Erick Gonzalez, (more)

Famous ones that checks if non-negative integer is a power of 2 or


not:
1) v && !(v & (v - 1))
2) v && (v & -v) == v
First left side of && checks whether v is 0 or not. Right side performs the check
for powers of 2.
How (1) works:
v-1 flips the least significant standing bit to 0, and flip all zeros that follow that
bit to 1.

Example:

More Related Questions

So if you & v-1 with v you get zero if there is only one standing bit (i.e. powers
of two). This does not work if v is zero, hence left side of && first checks if v is
zero.
How (2) works:
(v & -v) gets least significant standing bit of v.

Examples:
If v = 6
&

If v = 4
&

If there is only one standing bit (v & -v) is equal to v. As a side note, (v & v) trick to get least significant standing bit is also used in Binary Indexed Tree,
and it is a cool bit trick on its own.
Note: As Brad Bazemore mentions in the comment, if v is negative all that
this trick does is two's complement
Note 2: As Anders Kaseorg pointed out in the comment I initially
misinterpreted Brad Bazemore's comment and edited my answer stating that
replacing v with -v will solve the problem with v with negative value, but there
is no such thing as power of 2 that is negative, so I removed that part of my
edit. In summary, make sure that an integer is non-negative before using this
trick to find out whether it is a power of 2 or not
Updated 22 Dec, 2012.
Upvote 97

Downvote Comments 7+ Share

Pratyush Kumar, #5340000


31 upvotes by Sayak Kolay, Niharika Kohli, William Flaherty, (more)

Compute the sign of an integer.


1 int v;

// we want to find the sign of v

2 int sign;

// the result goes here

3
4 // CHAR_BIT is the number of bits per byte (normally 8).
5 sign = -(v < 0); // if v < 0 then -1, else 0.

Detect if two integers have opposite signs.


// input values to compare signs

1 int x, y;
2

3 bool f = ((x ^ y) < 0); // true iff x and y have opposite signs

Compute the integer absolute value (abs) without branching.


1 int v;

// we want to find the absolute value of v

2 unsigned int r;

// the result goes here

3 int const mask = v >> sizeof(int) * CHAR_BIT - 1;


4
5 r = (v + mask) ^ mask;

Compute the minimum (min) or maximum (max) of two integers


without branching.
1 int x;
2 int y;

// we want to find the minimum of x and y

3 int r;

// the result goes here

4
5 r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
6
7 r = x ^ ((x ^ y) & -(x < y)); // max(x, y)

Counting bits set, Brian Kernighan's way


1 unsigned int v; // count the number of bits set in v
2 unsigned int c; // c accumulates the total bits set in v
3 for (c = 0; v; c++)
4 {
v &= v - 1; // clear the least significant bit set

5
6 }

Computing parity.
1 unsigned int v;

// word value to compute the parity of

2 bool parity = false;

// parity will be the parity of v

3
4 while (v)
5 {
6

parity = !parity;

v = v & (v - 1);

8 }

Reverse bits.
... (more)
Upvote 31

Downvote Comments 2

Share

Vishnu Jayvel, Amazon Summer Intern 2014


11 upvotes by Ninad Kale, William Flaherty, Edde Yang, (more)

if (number&1)==1
then number is odd
else
number is even
This is logic is very famous and question based on this is frequently asked in
programming contest
P.S. as Raghavan Santhanam pointed out this logic wont work if the number is
float type
Written 25 Apr, 2013.
Upvote 11

Downvote Comment 1

Share

Shrey Banga, e-itinerant


26 upvotes by Sumeet Jain, Sandeep Kumar K, Abhishek Chanda, (more)

Quake's Fast Inverse Square Root[1] relies largely on bit manipulation to


approximate inverse square roots. Here's the code (with original comments) if
you can understand it:
1 float Q_rsqrt( float number ){
2

long i;

float x2, y;

const float threehalfs = 1.5F;

5
6

x2 = number * 0.5F;

= number;

= * ( long * ) &y;

// evil floating point bit level hacking

= 0x5f3759df - ( i >> 1 );

// what the fuck?

10

= * ( float * ) &i;

11

= y * ( threehalfs - ( x2 * y * y ) );

// 1st iteration

12 //

= y * ( threehalfs - ( x2 * y * y ) );

// 2nd iteration, this can be removed

13

return y;

14 }

A good explanation of the code can be found here [2].


[1] http://en.wikipedia.org/wiki/Fas...
[2] http://blog.quenta.org/2012/09/0...
Updated 6 Dec, 2012. Asked to answer by Sumeet Jain.
Upvote 26

Downvote Comments 2

Share 1

Satpal Parmar, Linux system programmer


21 upvotes by Sumeet Jain, Tamil Selvan, Shrey Banga, (more)

Two amazing list of bit twiddling hacks:


1. http://graphics.stanford.edu/~se...
2. http://hackersdelight.org/HDcode...
Stackoverflow list of questing with bit twiddling tag:
1. http://stackoverflow.com/questio...
Good intro for beginners:
1. http://www.catonmat.net/blog/low...

Written 23 Oct, 2012.


Upvote 21

Downvote Comment Share

Pratik Mehta, Realm of no-mind


9 upvotes by Vishnu Jayvel, Aswin Murugesh, Souvik Parial, (more)

Program to return the non repetitive integer from an array set:


1 int array[9]={3,4,1,3,1,7,2,2,4};
2

int remaining=0;

for(int i=0;i < 9;i

remaining^=array[i];

cout <<

remaining

<<

endl;

Avoid two loops and insted use bitwise XOR so simple!


Written 29 Jun. Suggestions Pending
Upvote

Downvote Comments 2+ Share

Tamil Selvan, Common Lisper.


9 upvotes by Sumeet Jain, Anindya Mozumdar, Prasaanth Muralidharan, (more)

Apart from Stanford Bit Twiddling hacks


There's book called Hackers Delight http://www.amazon.com/Hackers-De...
Its where you learn all your bit Tricks. One of the Awesome book with
somewhat strange Title. If you really really like Bit hacking this is the Book to
Read. Y ou can also get ideas from accompanying website
(http://www.hackersdelight.org/ )
Mit Courseware on Performance Engineering on Software Systems

(http://ocw.mit.edu/courses/elect... ) Also really Useful. Download the videos


and enjoy hacking .
Written 23 Oct, 2012.
Upvote

Downvote Comment Share

Shivaraj Shetty
7 upvotes by Vishnu Jayvel, Abhishek Tapadar, Surya Kant Verma, (more)

I love following snippet to find the number which doesn't have a pair in a
array where all elements are repeated twice while one of them is only once.
Bit manipulation (xor) allows to find this at a complexity of O(n).
odd_one = 0;
for ( i = 0; i < n ; i++)
odd_one ^= array[i];
Written 7 Jun.
Upvote

Downvote Share

Siddharth Subramanian, MS CS, UT Austin


11 upvotes by Shrey Banga, Sumeet Jain, Sugavanesh Balasubramanian, (more)

Y ou can read this article: http://community.topcoder.com/tc...


tricks. Some of them are:

for some nice

Reversing a bits in an integer:


1 x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1);
2 x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2);
3 x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4);
4 x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8);
5 x = ((x & 0xffff0000) >> 16) | ((x & )0x0000ffff) << 16);

Iterate through all k-element subsets of {0, 1, ..., N - 1}


1 int s = (1 << k) - 1;
2 while (!(s & 1 << N))
3 {
4

// do stuff with s

int lo = s & ~(s - 1);

// lowest one bit

int lz = (s + lo) & ~s;

// lowest zero bit above lo

s |= lz;

// add lz to the set

s &= ~(lz - 1);

// reset bits below lz

s |= (lz / lo / 2) - 1;

// put back right number of bits at end

10 }

... and much more. The explanation for the above code snippets are also
available in that article.
Updated 25 Oct, 2012.
Upvote 11

Downvote Comment Share

Ilya Veygman, container of multitudes


19 upvotes by Abhishek Srikanth, Balaji Sridharan, Burak Ycesoy, (more)

Not my own technique, but I always liked the in-place swap trick:
1 a ^= b;
2 b ^= a;
3 a ^= b;

This works because a XOR a is always 0, and a XOR b is the same as b XOR a.
So what happens is you get,
a := a XOR b
b := b XOR a, but a is now a XOR b, so b := a XOR b XOR b, which works out
to being a
Now the last step, remember that a is currently a XOR b. Further XORing that
with b, which is now a, will cancel out the original a and leave you with just b.
Voila! Swap with no additional memory needed
Edit: fixed to the correct source, since my original answer was actually me
being lazy and typing the shorthand. Thanks to Xuan Luo
Written 24 Jan, 2013.
Upvote 19

Downvote Comments 3+ Share

Nalan KR
Edit Bio Make Anonymous

Add your answer, or answer later.

Top Stories from Your Feed


A NSWER PROMOTED IN TOPIC
C HENNA I, T A M IL
NA DU, I NDIA. 10h ago

India: Dogs : What is the best way


to protect myself from angry
street dogs when travelling to a
new locality at night?
Meenakshi Nandhini, Alice in
Quoraland
17 upvotes by Nalin Savara, Harshit Agarwal, Surya
Sankar, (more)

For this answer, I rely on more than two


decades of first-hand experience with
navigating streets 'owned' by Chennai street
dogs. :) Reference: Indian pariah dog
Aggressive behaviour as discussed ...
Read In Feed

A NSWER A DDED TO TOPICS


EDUC AT ION
A ND 2 MORE. Thu

What is something that you read


recently and is worth sharing?
) A technology freak ,
Hiteeksha Mathur,
who loves...
2.4k upvotes by Akhil Gulecha, Krishna Sa, Akash
Ramesh, (more)

Whatsapp status of a friend:'Work until you don't have to introduce


yourself '

A NSWER A DDED TO TOPIC


M A T HEM A T IC S. Sun

Why does 1+1 equal 3?


Gourav Meena, Web Designer and
Developer
34 upvotes by Shishir Jain, Siddharth Nilawar,
Justas Brazauskas, (more)

I thought the guy who asked the question


was stupid, but after reading the answers I
am 100% convinced that people answering
the question are more stupid. I mean why
would you even try to answer su...

Written 3 Aug.

Read In Feed

Read In Feed

Das könnte Ihnen auch gefallen