2023-11-14

Deep dive into Bit manipulation

So Bit manipulation and bitwise operaters. What is it? Well it's a way to manipulate single bits in a byte. You can use it to set a bit to 1 or 0 in the binary code. For example we will take the value 4, the binary code of 4 is 00000100. Lets say we want to double it in this case. Well we can do that in 2 ways. Or we just multiply the 4 by 2 and we get 8 but lets say we want to do it by bit manipulation. That's pretty easy! We can use the left shift operator and shift the bits to the left by one. If we do this our 00000100 (4) will become 00001000 (8). Now in this case it isn't really a lot more of a performance gain and we sacrifice readability and most compilers are optimised for normal multiplying operations. But in my case I used the XOR operator to swap 2 values without using a temp variable.

Then the other question is if it was worth it to learn more about it? Well I think it was. I learned something new and I can use it in the future. Also not everything that I learn is to use it on a daily basis. It's more because I'm really passionate about learning new concepts and just making my knowledge bigger. It was also just nice to get one evening of a break on push_swap because all the 42 students know that it's not everybody's favorite project. I'm currently at this time writing the sorting algorithm and I'm almost done with it. When I'm done expect a blog post about it!

C programming