Information

Author(s) Arthur van Stratum
Deadline Καμία προθεσμία
Submission limit No limitation
Category tags s2, level2, category_bit

Ετικετές

Συνδεθείτε

[S2] Bitwise operation: cycling bits

In this exercise, we will work with operation on bits. When we speak about the position of a bit, index 0 corresponds to lowest order bit, 1 to the second-lowest order bit, ...

In C source code, you can write a number in binary (base 2) by prefixing it via 0b., e.g. 0b11010 = 26.

This exercise will introduce some non-standard data types which guarantee that the variable has a fixed number of bits. Indeed, on some machines, a int could use 2, 4 or 8 bytes. Hence, if we want to perform bitwise operations, we have to know first on how many bits we are working.

For this, C introduces a new class of variable types :

  • int8_t (signed integer of 8 bits)
  • uint8_t (unsigned integer of 8 bits)
  • uint16_t (unsigned integer of 16 bits)

You can mix uint or int with bit-lengths 8, 16, 32 and 64). These types are defined in <stdint.h>


Write the body of a function cycle_bits, which cycles all bits from n places to the left, according to the formula x[(i+n)%32] = x[i], where x[i] is the i-iest bit of x.

Here is a simple example with bytes. Consider byte 0b01101011. If n is set to 1, then cycle_bits would return 0b11010110. If n is set to 4, then cycle_bits would return 0b10110110.

uint32_t cycle_bits(uint32_t x, uint8_t n) {