c - ANDing with different bit lengths -


i have following:

void calculate(unsigned long num1, unsigned long num2){    int32_t invertednum2 = ~(num2);    // yields 4294967040    printf("%d\n", invertednum2);      // yields 255     // num1 3232236032    int32_t combine = (int32_t) num1 & num2;    printf("%d\n", combine);           // yields 0??? } 

i'm trying , num1 , num2 result be:

   000000000000000011111111 

i'm not sure if i'm anding correctly 2 different bit lengths or if should cast.

any appreciated!

thanks

you can't , different bit lengths in c, because can't apply binary operator (except shift) on operands of different types. if write code operands different types, c compiler first convert them same type (and same size) before doing operations. there 7 pages in c spec (section 6.3) devoted details of precisely how happens.

as result when have:

int32_t combine = (int32_t) num1 & num2; 

and num1 , num2 both unsigned long , 64 bits, happen is:

  1. the cast truncate num1 32 bits
  2. the , has different operand types (int32_t , uint64_t), int32_t sign extended 64 bits.
  3. the , performed on 2 64 bit values
  4. the result truncated 32 bits , stored in combine

now since num1 3232236032 (0xc0a80200), steps 1 , 2 convert 0xffffffffc0a80200, anded num2, , top 32 bits thrown away.

in contrast, if had:

int32_t combine = (int32_t)(num1 & num2); 

it 64 bit , on num1 , num2, , trunctate 32 bits store in combine. while quite different first case, resulting value stored in combine same -- intermediate value (the result of bitwise and) noone ever sees different. result, compiler free rearrange things , generate exact same code these 2 cases.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -