c

cast without * operator


Could someone explain to me what's happening to "n" in this situation?

main.c

unsigned long temp0;
PLLSYS0_FWD_DIV_A_DECODE(n);

main.h

#define PLLSYS0_FWD_DIV_A_DECODE(n) ((((unsigned long)(n))>>8)& 0x0000000f)

I understand that n is being shifted 8 bits and then anded with 0x0000000f. So what does (unsigned long)(n) actually do?

#include <stdio.h>

int main(void)
{
    unsigned long test1 = 1;
    printf("test1 = %d \n", test1);
    printf("(unsigned long)test1 = %d \n", (unsigned long)(test1));

return 0;
}

Output:

test1 = 1 
(unsigned long)test1 = 1

Solution

  • It widens it to be the size of an unsigned long. Imagine if you called this with a char and shifted it 8 bits to the right, the anding wouldn't work the same.

    Also just found this (look under right-shift operator) for why it's unsigned. Apparently unsigned forces a logical shift in which the left-most bit is replaced with a zero for each position shifted. Whereas a signed value shifted performs an arithmetic shift where the left-most bit is replaced by the dropped rightmost bit.

    Example:

    11000011 ( unsigned, shifted to the right by 1 )
    01100001
    
    11000011 ( signed, shifted to the right by 1 )
    11100001