From c82d9414ca866252629604eb27141577731c5e00 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 24 Apr 2023 20:35:27 +0200 Subject: [PATCH] circ shift --- CMakeLists.txt | 1 + src/circular_shift.c | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/circular_shift.c diff --git a/CMakeLists.txt b/CMakeLists.txt index ac4b0b5..fa149b5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,7 @@ add_executable( arrToBin src/arrToBin.c ) add_executable( ascii src/ascii.c ) add_executable( calculator src/calculator.c ) add_executable( callreference src/callreference.c ) +add_executable( circular_shift src/circular_shift.c ) add_executable( complex src/complex.c ) add_executable( dividableBy7 src/dividableBy7.c ) add_executable( structdump src/structdump.c ) diff --git a/src/circular_shift.c b/src/circular_shift.c new file mode 100644 index 0000000..5ca845b --- /dev/null +++ b/src/circular_shift.c @@ -0,0 +1,36 @@ +/** + * C implementation for bit rotating: + * see https://en.wikipedia.org/wiki/Circular_shift#Implementing_circular_shifts + */ + + +/* + * Shift operations in C are only defined for shift values which are + * not negative and smaller than sizeof(value) * CHAR_BIT. + * The mask, used with bitwise-and (&), prevents undefined behaviour + * when the shift count is 0 or >= the width of unsigned int. + */ + +#include // for uint32_t, to get 32-bit-wide rotates, regardless of the size of int. +#include // for CHAR_BIT + +uint32_t rotl32 (uint32_t value, unsigned int count) { + const unsigned int mask = CHAR_BIT * sizeof(value) - 1; + count &= mask; + return (value << count) | (value >> (-count & mask)); +} + +uint32_t rotr32 (uint32_t value, unsigned int count) { + const unsigned int mask = CHAR_BIT * sizeof(value) - 1; + count &= mask; + return (value >> count) | (value << (-count & mask)); +} + +uint32_t main() { + uint32_t x = 0x1337; + uint32_t rotr = rotr32(x, 17); + uint32_t rotl = rotl32(x, 17); + printf("original:\t%032b - 0x%x - %d\n", x, x, x, x); + printf("rshifted:\t%032b - 0x%x - %d\n", x, rotr, rotr, rotr); + printf("lshifted:\t%032b - 0x%x - %d\n", x, rotl, rotl, rotl); +}