c – MSP430FR5739 rotate bits in 16-bit unsigned integer

Portable

uint16_t rotate_right(uint16_t value, uint16_t positions) 
{
    return (value >> positions)  | (value << (16 - positions));
}

GCC style asm

uint16_t rotate_right_asm(uint16_t value, uint16_t positions) {
    __asm__(
        "RRC %[val]\n"          // Rotate right through carry
        "DECD %[pos]\n"         // Decrement positions
        "JNZ $-2\n"             // Loop if not zero
        : [val] "+r" (value)    // Output operand
        : [pos] "r" (positions) // Input operand
    );
    return value;
}

TI style ASM (not tested)

uint16_t rotate_right_TI(uint16_t value, uint16_t positions) 
{
    __asm__ (
        "1: RRC %0\n"
        " DEC %1\n"
        " JNZ 1b\n"
        : "+r" (value), 
          "+r" (positions)
    );
    return value;
}

TRhen use them in your function:

void rotate_bits_right_16bit(unsigned int *address, unsigned char num_rotates)
{
    uint16_t val = *(uint16_t *)address;
    *(uint16_t *)address = rotate_right_asm(val, num_rotates);  
}

void rotate_bits_right_16bit_safe(unsigned int *address, unsigned char num_rotates)
{
    uint16_t val;
    memcpy(&val, address, sizeof(val));
    val = rotate_right_asm(val, num_rotates);  
    memcpy(address, &val, sizeof(val));
}

godbolt.org/z/zKfnrWKEj

Read more here: Source link