c++ - Write a function to copy 0-15 bits into 16-31 -
how write function copy 0-15 bits 16-31?
unsigned int n = 10; // 1010 copyfromto(n); assert(n == 655370); n = 5; copyfromto(n); assert(n == 327685); n = 134; copyfromto(n); assert(n == 8781958);
you want copy bits in 0-15 16-31. should understand multiplying 2 equivalent shifting bits of number once left (moving higher bits).
if number n
, n << 16
shifting number 16 bits left. equivalent multiplying n 16th power of 2, happens 65536.
to copy bits, , keep original bits in 0-15, command n = n + (n << 16);
should work. however, issue (as pointed out in comments), upper 16-31 bits still set in n +
term. need clear these bits. note 65535 corresponds 2^16 - 1, , have first 0-15 bits 1, , others 0. correct command n = (n && 65535) + (n << 16);
Comments
Post a Comment