Circular 4-bit rotations (for fun)

Discussion in 'Programming General' started by 146918496, Oct 4, 2017.

Circular 4-bit rotations (for fun)
  1. Unread #1 - Oct 4, 2017 at 2:37 PM
  2. 146918496
    Joined:
    Oct 1, 2017
    Posts:
    29
    Referrals:
    1
    Sythe Gold:
    30

    146918496 Member
    Banned

    Circular 4-bit rotations (for fun)

    I came up with the idea of circular rotations on each *box* of 4 bits (counter-clockwise in this case) earlier today and decided to try and write a function that would save the values back to the 2 16-bit integers. It was a pretty fun thing to write :)

    [​IMG]

    Code:
    #include <stdio.h>
    #include <stdint.h>
    
    void rotate_4b(uint16_t *v1, uint16_t *v2)
    {
        int n = 0;
        while (n < 16)
        {
            int swap_v1 = (((*v1 >> n) & 1) << 1) | ((*v2 >> n) & 1);
            int swap_v2 = ((*v1 >> n) & 2) | ((*v2 >> (n + 1)) & 1);
            *v1 = (*v1 & ~(3 << n)) | (swap_v1 << n);
            *v2 = (*v2 & ~(3 << n)) | (swap_v2 << n);
            n += 2;
        }
    }
    
    int main(void)
    {
        int i = 0;
        uint16_t v1 = 0x0A0A;
        uint16_t v2 = 0xB0B0;
    
        for (; i < 4; ++i)
        {
            rotate_4b(&v1, &v2);
            printf("0x%.4x\n", v1);
            printf("0x%.4x\n\n", v2);
        }
    
        return 0;
    }
    Code:
    /*
    before:
    0001 0010 0011 0100 = 0x1234
    0101 0110 0111 1000 = 0x5678
    
    after:
    0111 0100 0111 1000 = 0x7478
    0000 0011 0011 0100 = 0x0334
    
    0 <- 1

    Section is not that active, so I'll post this even though it's not terribly useful.
     
    ^ Eru likes this.
    Last edited: Oct 4, 2017
< SQL Server | Java global hotkeys without use of JNI? >

Users viewing this thread
1 guest


 
 
Adblock breaks this site