C Code Examples: Array Rotations

This topic was published by and viewed 1707 times since "". The last page revision was "".

Viewing 1 post (of 1 total)
  • Author
    Posts

  • DevynCJohnson
    Keymaster
    • Topics - 437
    • @devyncjohnson

    Rotate an Array of Bytes to the Left

    void array_rotl(uint8_t *array, const size_t len, const uint32_t num_shifts) {
        // Rotate an array to the left in-place
        if ((len > 0x02) && (num_shifts != 0x00)) {
            register uint32_t i, j;
            register uint8_t first;
            for (i = num_shifts; i != 0x00; --i) {
                first = array[0x00];
                for (j = 0x00; j < (uint32_t)(len - 0x01); ++j) array[j] = array[j + 0x01];
                array[j] = first;
            }
        }
    }

    Rotate an Array of Bytes to the Right

    void array_rotr(uint8_t *array, const size_t len, const uint32_t num_shifts) {
        // Rotate an array to the right in-place
        if ((len > 0x02) && (num_shifts != 0x00)) {
            register uint32_t i, j;
            register uint8_t last;
            for (i = num_shifts; i != 0x00; --i) {
                last = array[len - 0x01];
                for (j = (uint32_t)len; --j;) array[j] = array[j - 0x01];
                array[0x00] = last;
            }
        }
    }

    Rotate Char Array of Bytes to the Left

    void chararray_rotl(char *array, const size_t len, const uint32_t num_shifts) {
        // Rotate a char array to the left in-place
        if ((len > 0x02) && (num_shifts != 0x00)) {
            register uint32_t i, j;
            register char first;
            for (i = num_shifts; i != 0x00; --i) {
                first = array[0x00];
                for (j = 0x00; j < (uint32_t)(len - 0x01); ++j) array[j] = array[j + 0x01];
                array[j] = first;
            }
        }
    }

    Rotate Char Array of Bytes to the Right

    void chararray_rotr(char *array, const size_t len, const uint32_t num_shifts) {
        // Rotate a char array to the right in-place
        if ((len > 0x02) && (num_shifts != 0x00)) {
            register uint32_t i, j;
            register char last;
            for (i = num_shifts; i != 0x00; --i) {
                last = array[len - 0x01];
                for (j = (uint32_t)len; --j;) array[j] = array[j - 0x01];
                array[0x00] = last;
            }
        }
    }

    Further Reading

Viewing 1 post (of 1 total)