Here we discuss how to clear the least significant bits (LSB) in an integer up to a given position pos (including pos). (Check out this post for clearing the MSBs up to a given position.) What doe...

# Bitwise nuggets: clear the most significant bits up to a given position

Here we discuss how to clear the most significant bits (MSB) in an integer up to a given position pos (including pos). (Check out this post for clearing the LSBs up to a given position, or this one...

# Bitwise nuggets: get bit at position

Here is how to obtain the bit at a given position pos in an integer. Bit positions start at 0, and the bit at position 0 is the least significant bit (LSB). The idea is to apply a mask to the inte...

# Bitwise nuggets: count set bits

If we want to count the number of set bits (i.e. bits that are 1) in an int, we can check whether its least significant bit (LSB) is 1, count it as set if applicable, then right-shift the int by on...

# Bitwise nuggets: count total bits

If we want to count the total number of bits in an integer, we can divide that number by two until it becomes zero, counting a bit at each step. Here is how this can be implemented in C: #include...

# Bitwise nuggets: invert the n least significant bits

Suppose we want to invert the n least significant bits in a number. For example: 2019 = 11111100011 |||| 2028 = 11111101100 If we invert the least significant 4 bits in the number ...

# Bitwise nuggets: convert an integer to a binary string

When we want to display an int as a binary string, we need a utility function that builds the string representation of the integer. We do this from the least significant bit (LSB) up to the most si...

# How to read safely from stdin in C

Ah, C and strings. When reading from stdin, we can use fgets(str, n, stdin) to read at most n - 1 characters into a char array pointed to by str. We can also create a utility function...

# Implementing a vector in C

Suppose we need a generic vector data structure in C, where by generic we mean it can handle any type of data. A vector uses an underlying array, therefore it supports index-based access to its ele...

# (Anonymous) unions in C

The first time I had to explain to students why a C union may sometimes come in handy, I came up with this example. As my students had only been exposed to C for about 15 hours, I needed to refrain...