I am trying to divide a integer (2's complement) by a power of 2 and then round that number toward zero. I am only allowed to use bitwise operators such as shifts, ~ ^ & | etc. I've came up with 2 expression but they dont seem to work. Can anyone help me out.

x/(2^y)

1) x>>y example: 15/2^1=7 00001111(15) >>1 = 00000111 (7) Why doesn't this work?

2) a=~x
b=a>>y
c=~b

example: 15/2^1=7 00001111(15), ~15 = 11110000, shift by y = 11111000, negate c = 00000111 = 7
Can someone explain why this doesnt work either?

<< (LS) can be seen as a multiplication by 2
>> (RS) can be seen as a division by 2
so a number can be divided in terms of powers of 2 as:

int Divide ( int intVal, int powerOfTwo )
{
  if( !powerOfTwo )
     return intVal;
  else
     return intVal >> (1 << powerOfTwo) ; 
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.