r/C_Programming • • Jul 05 '26
Question How do you understand bitwising tricks
Im not Talking about basic operations, setting flags or bitshifting.
I speak about the tricks operations involving bitmasks and stuff.
I just can’t get how people get familiar with it.
I guess there is no magic way to understand, I just have to keep studying it, but do you guys have any resource or mental tips that can make me more familiar with these ?
Thank you
22
Upvotes
11
u/invokeinterface Jul 05 '26
I think looking through and messing around with some of Sean Eron Anderson's bit hacks could be a great way to get familiar with it all. Beyond that, all I can really say is that you should try and understand binary as well as you possibly can. Even if you already understand how it works.
https://graphics.stanford.edu/~seander/bithacks.html
27
u/Bergergi Jul 05 '26
Warren: 'Hacker's Delight' covers a lot of cool bit twiddling tricks.
9
u/HashDefTrueFalse Jul 05 '26
It's a lot easier to understand if you're primed on the basics of digital logic and a tiny bit of boolean algebra. Basically, be familiar with the different logic gates, the truth tables for them, and how to simplify expressions (or circuitry/arrangements) of them. Bitwise operations are just doing those things to the bits in a... bitwise fashion. It's all fairly easy stuff usually taught at the beginning of an electronics or CS course/degree.
Hacker's Delight is a great book but I don't think that it's the best book for learning the basics above. It's more of a showcase of interesting bit hacks.
2
u/Jalebdo Jul 06 '26
I did all the leetcode easy(and a few medium) bitwise problems. Through doing those problems I found myself doing a lot of bitwise operations on pen and paper. Simply going through those problems I feel has given me the way of bitwise thinking I believe you're looking for.
1
u/texruska Jul 05 '26
Once you get the basics down (what operations you can do) then there isn't much else to do except walk through them
Some of the wonky bit manipulation optimisations I've seen at work took me ages to understand step by step and every time I forget the details and have to carefully re-read the documentation
1
u/Hawk13424 Jul 05 '26
As a computer engineer, I find them trivial. Just basic Boolean logic problems. Bit of Boolean algebra and Karnaugh maps.
6
u/WittyStick Jul 05 '26 edited Jul 05 '26
Just look at the truth tables.
There are 16 possible bit-pattern results for two inputs - the others I've not included are
A,B,~A,~B,TandF- as these depend on either one or none of the inputs.To get some intuition for what each does.
ANDsets bits when both inputs are set. This is usually used to TEST if an inputxcontains specific bits. Eg, if we want to test if the bits set inyare set inx, we test if the result of and equalsy.ORsets bits in the inxwhich are set iny. This is often used to combine flagsORis also used to add atagto a value - eg:ANDNOTreverses this - given a tagged value and a tag, it removes the tag and gives back the value.XORis used for many tricks, and is even used in cryptography, because it has the property.XORis also used to clear values when the same input is used for both left and right operands.XNOR, or more intuitively,EQV, tests if two inputs are equal. But unlike==, it does not returnbool, but a value where every bit is set if the values are equal - which is the value-1in twos complement.What also may be useful is to know how the operations relate to one another. They form a lattice which can be seen in this Hasse diagram
2
u/partyboy690 Jul 05 '26
Conceptually I do understand it quite well and how I always describe it to people who don't get it is to think about it as an array of booleans and the masks act as a tool to query one or more of those indexes which I think you understand from your post.
Where things can get very interesting is using bitwise tricks to encode and decode data especially in the context of a binary protocol field and using masks for decoding.
Think about an 8 bit field and bits 0 to 4 represent a certain amount of information so with 5 bits you can represent 32 distinct entities, eg. 00000, 00001, 00010, 00011... 11110, 11111 and so the last three bits are for something else and when decoding we need to use a mask to ignore those bits and we can only test the first 5 then.
So to interpret your value you would do something like this.
uint8_t value = input & 0x1F;and the value could be an enum. You can expand this out to to larger unsigned int types too and you just need to write your masks appropriately.There's rotating bits that I don't know off the top of my head how it works but it's a known concept in hashing/crypto and it can be searched as needed but the key point is to understand the different operations and how you can combine them to create coherent logic out of them.
3
u/am_Snowie Jul 05 '26
Like what?
2
u/Conscious_Support176 Jul 05 '26
Not sure what you’re asking. You understand setting flags? Bitmasks are just a way of working with a subset of the bits within a byte. Setting and reading individual flags is exactly the same thing, except it’s for just one of the bits.
1
u/ANixosUser Jul 05 '26
a lot of it is just noticing when powers of two are involved is a big part of the magic. i dont use them myself because i dont write performance-critical software (at least not that much) and they are incredibly hard to read if undocumented (and i dont like comments explaining code).
1
u/True_Fig983 Jul 05 '26
Practice
1
u/juancn Jul 05 '26
Mainly just do a lot of them over time and at some point it just clicks.
For the more advanced ones you need to be familiar with modular arithmetic (first few chapters of Knuth’s “Concrete Mathematics”)
Stanford graphics has a nice catalog of the common ones https://graphics.stanford.edu/~seander/bithacks.html
1
u/sciencekm Jul 05 '26
There is bit-slicing which is done with Boolean algebra.
1
u/dmc_2930 Jul 05 '26
You just do it enough until it comes naturally.
1
u/mykesx Jul 06 '26
Here's a thought experiment.
You have a 320x200 monochrome display. The bitmap is 1 bit per pixel, 8 pixels per byte, 320/8 = 40 bytes per row. You need bit operations to turn on, off, or read a pixel is on or off.
The first pixel in the first row is bytes[0] & (1<<7). The second pixel is bytes[0] & (1<<6). See the pattern?
1
u/Independent_Art_6676 Jul 07 '26
depends on how far along you are? A full on course in logic and boolean algebra is a starting point, but then you get the cool stuff outside of math too like swap with xor or multiply/divide by shifting and so on. Karnaugh maps are pretty awesome for combining multiple bits in efficient, hard to see ways. Memorization of stuff you run across will happen too.
A lot of this stuff is obsolete because its slower than modern CPU instructions. Eg the tricks to count how many bits are set in a flag-integer is moot if your CPU has an instruction that does that for you. Swapping with xor is incredibly slow compared to other methods... etc. Seek out ways to avoid loops or branches for some easy performance tweak bit tools, but pay attention to what is cute vs what is actually effective.
1
u/Vollink Jul 09 '26
I have to mention here, because I didn't see anybody else mention it explicitly. HEX NUMBERS MAP TO 4 BINARY BITS CLEANLY.
This seems silly, until the numbers get bigger. My examples are tiny, but what about a
uint64_t, and you need to set the 421st bit?I need to set the 12th bit?
Also, as someone else said, read a few chapters on binary algebra, that is what made all this stuff click to me.
1
u/mykesx Jul 05 '26
C is known as a shorthand for assembly language. You use all thes bitwise boolean algebra operations in both C and assembly language all the time.
The bit operations are detailed here
https://github.com/mschwartz/assembly-tutorial
-7
u/TheOtherBorgCube Jul 05 '26
Mostly, you don't.
Your normal course of action is to be writing code that is clear and obvious to the averagely competent C programmer.
If you throw a bit-hack into your code, you need to add one hell of a comment explaining why it was necessary, what it does and why the simple equivalent isn't good enough (space, speed, whatever).
The same reason people come up with bit hacks is largely the same reason that people come up with quines and IOCCC entries - smart obsessives with too much time on their hands.
Like a lot of complicated and clever stuff in C, the number of actual cases you'll find in real code doing real work in the real world is vanishingly small.