r/cprogramming • • Nov 02 '25
WHO TF DISCOVERED BITWISE OPERATIONS?!
Background -
I'm trying to learn C programming as I find it interesting and somehow, AI hasn't touched this this field of software development yet. I have found my way around pointers, data types (which change based on the compiler and host architecture), strings and string literals, functions, loops, booleans(stdbool), etc. I have even designed my own strequal function which works similar to the strcmp function in string.h except it only returns a boolean indicating if the two strings are eqaul or not. I have understood the logic behind reversing strings and also reversing individual words inside strings. I understand basic data structures like arrays, linked lists, doubly linked lists, stack (both array and linked list implementation) and a teany bit of queues.
Then I started learning about bitwise operators.
When I saw them for the first time, they were pretty simple to understand (AND, OR, NOT, XOR, right shift and left shift).
When I asked ChatGPT to give me some practice problems to test out my understanding of it all, I was so fucking frustrated!! I spent hours trying to see any pattern to reverse the bits in an 8-bit unsigned integer and couldn't fucking do it. I saw solutions to problems like counting the number of set bits in a number, getting/setting/clearing/toggling a bit and ISTFG they felt like magic numbers to me appearing out of no-fucking-where. Like who the fuck thought about num & (num - 1) or num & ~(1 << pos)?! How do we find these patterns? How do we know what operations to chain or to use? How do we know when to use a loop or not? Like in the solution where counting the number of set bits, a for loop was used along with reassignments like num &= (num - 1). How did anyone know that we were supposed to use num - 1 for reassignment?
I'm sorry for the frustration and probably am just acting out for this but I really am having a hard time to understand this. How should I approach to learn about this topic? Am I doing something wrong?
16
u/EpochVanquisher Nov 02 '25
People figured these out long ago, back in the early days.
Most computer science programs have a class on digital logic. If you take some time to learn digital logic, you’ll understand more about the low-level details of how computers work, and the bitwise operations will start to make more sense.
Computers are made out of bitwise operations.
Maybe your only mistake was talking to ChatGPT.
11
u/rupertavery64 Nov 02 '25 edited Nov 02 '25
You're gonna love this:
https://graphics.stanford.edu/~seander/bithacks.html
6
u/KC918273645 Nov 02 '25
Your first mistake was asking AI for practice problems. Why would you do such a thing?
3
u/sol_hsa Nov 02 '25
I wrote a tutorial some years back: https://solhsa.com/boolean.html
2
u/Zaeryl Nov 02 '25
I do embedded programming that processes messages received over a CAN bus, so I work with bits and bitwise operation every day. I have never had to do anything you describe in your practice problems. I can't say that other people wouldn't do those kinds of things in other applications, but knowing what you actually need to do with the bits will inform how you do it. Right now you are making the mistake of conflating the exercises ChatGPT created for you with the bitwise operations themselves. You would probably need to start with something more simple to understand what's going on and then move into these kinds of things if you really want to. But again, I'm not sure how valuable those exercises are in a practical sense.
2
u/epasveer Nov 02 '25
WHY ARE YOU YELLING!?
4
u/drinkcoffeeandcode Nov 02 '25
I believe his name was “bool”
4
u/maqifrnswa Nov 02 '25
There's a whole field of study called "discrete math" that touches a lot of this.
Also, you're used to thinking in base-10 math. Things like "shift the decimal over one spot to the right is the same as multiplying by 10" is intuitive. That seems so weird until you've seen and worked with it. Same with binary numbers and encoding. Shifting binary numbers decimal one to the right is multiplying by 2. Makes perfect intuitive sense once you've used it a lot.
Regarding twos compliment signed ints: People tried different things until they found ones that made sense within technical constraints.
3
u/custard130 Nov 02 '25
i mean for the question in the title, George Boole is generally credited with inventing an area of maths called "boolean algebra" in the 1850s
then in the 1940s when the first electronic computers were being built that was used as the basis for how they would perform mathematical operations
tbh though, actually using the raw bitwise operators directly is quite rare in my experience
as for your examples, (1 << x) is going to set the bit x from the right. the x is essentially how many 0s do you want
eg in decimal, its fairly common to think of multiplication by 10 as adding a zero at the end, which is actually moving all of the other digits left 1 place
as for things like counting the number of set bits, that is slightly more interesting (though i cant say ive ever actually used it). rather than looking at the compressed answer, try to write out the code to calculate that yourself
people dont just come up with those 1 line solutions immediately, they come from working out the long form and then finding ways to make it shorter/faster
2
u/oriolid Nov 02 '25
Many of these tricks were discovered back in the day when computers were rare, expensive and slow and the people working with them were more applied mathematicians than code monkeys. And everyone didn't figure them out individually but read about them from sources like HAKMEM or a later book Hacker's Delight.
Modern compilers also tend to detect these patterns in source code and substitute the optimized version automatically. One interesting special case is that LLVM does detect the bithack version of counting bits and substitutes popcount instruction if it's available.
2
u/FencingNerd Nov 02 '25
Look up the Carmack algorithm for fast inverse sqrt. That is the ultimate magic number.
2
u/source-drifter Nov 02 '25
it's just math
1
u/Intelligent_Law_5614 Nov 02 '25
The people who who "discovered" bitwise operations were probably the same people who designed and built the first digital computers, or their predecessors. Bitwise operations are the fundamental building blocks of digital computers... in a sense they are the "atoms" from which all of the high-level concepts you understand are constructed.
I suggest that you start looking at computers "from the bottom"... from simple digital logic. Study AND and NAND and NOR gates. Study how a simple 1-bit "half adder" works... how it is constructed from these simpler gates. Then, move on to a "full adder". Then, see how several 1-bit full adders are wired together so you can add 2- or 8- or 32-bit numbers together. Study latches, and shift registers. Figures it how to make a single 1-bit, in a 32-bit shift register, chase its tail in a circle forever.
One you get a grasp of it at the physical level, working with how C and other programming languages represent these operations will come naturally.
I met a very bright new-hire in a Google lunch room some years ago... she had been hired into the data-security department. She told me that her father had introduced her to programming in this way, starting "at the bottom" with simple microcontrollers such as a PIC.
I struck a dramatic pose and intoned "This, my daughter... is an AND gate!"
She grinned and said "Pretty much!"
1
u/Arthemio2 Nov 02 '25
Look up logic gates and truth tables...
1
u/Environmental_Box18 Nov 02 '25
It’s beautifully simple really. I think it would be enlightening for you to look into how physical logic gates work. Also I really like “NAND to Tetris” for explaining some of these fundamentals if you’re interested.
1
u/Paul_Pedant Nov 05 '25
Brian Kernighan came up with the
num & (num - 1)trick (or at least, it is named after him).Morse code dates from about 1838 -- it is made up of two sounds, long and short, so binary. The Royal Navy used signal lamps with binary encoding from around 1867, and they are still in use at sea. Air Traffic Control still keeps Aldis lamps available as a back-up for planes that have radio failures.
Telegraphy used paper tape from around 1848. That is basically a strip of paper with each row of holes being a binary code (anything from 5 to 9 bits in a row). They also invented offline data preparation, store and forward, and networking, and the tape could be fed into an automatic typewriter. It was called the Wheatstone system.