0

I know the best way to divide a number by 2 is to move one bit to the left. What do I do if I am dividing by a multiple of 2 (for example 8), do I move over by 3 bits, here are my questions:

  1. How can I do such operations in C++, bit movement?
  2. How can I access higher byte of an int and lower byte of an int, if I wanted to swap their values?

I know these operations can be done at the assembly level because we are dealing with registers, I just don't know if we have access to such things in C++.

Chen Li
  • 151
  • 1
  • 2
  • 9
  • 3
    `<<` and `>>` and `|` and `&`. –  Dec 07 '12 at 14:43
  • 3
    Any decent compiler would optimize `x / 2`. See [this question](http://stackoverflow.com/questions/2580680/does-a-c-c-compiler-optimize-constant-divisions-by-power-of-two-value-into-shi) or [this one](http://stackoverflow.com/questions/235072/do-modern-compilers-optimize-the-x-2-operation-to-x-1) or [this other one](http://stackoverflow.com/questions/10681375/which-is-better-option-to-use-for-dividing-an-integer-number-by-2?lq=1). – fouronnes Dec 07 '12 at 14:43
  • 1
    If `one` bit shift divides by 2 `(2^1)`, then `three` bit shifts divides by ? – asheeshr Dec 07 '12 at 14:43
  • 1
    Google "c++ bit manipulation" and you'll find many tutorials. – NPE Dec 07 '12 at 14:46

1 Answers1

3

Accessing the higher/lower bytes of an integer, and swapping them can be done in at least two ways. Either a combination of >> and |, or with a union.

For example something like:

short swapped = (original<<8)|(original>>8);

will give you the two bytes of a 2-byte integer swapped. If you have a larger integer (e.g. 4 bytes), some more masking and shifting will be required, if all bytes are needed in some particularly shuffled order.

Optimizing divisions by multiples of 2 with right shift (>>) is a no-optimization. You should write readable code that gives a clear idea of what is intended. The compiler will trivially perform such micro-optimizations.

Damon
  • 67,688
  • 20
  • 135
  • 185
  • What do you mean, how will the compiler know to optimize "int x = 256/8;" – Chen Li Dec 07 '12 at 14:50
  • 2
    `256` and `8` are literals. The compiler will simply replace that with `int x = 32;` If you wrote something like `x = y / 8;` the compiler would turn it into `x = y >> 3;`. It is not necessary to write obfuscated code like that, the compiler knows to do these things. – Damon Dec 07 '12 at 14:54
  • All I need to do is put my problem in terms of multiples of 2, so instead of having: "int x = (65 - 1)/2", I should have "int x = 64/2" – Chen Li Dec 07 '12 at 14:55
  • `(65 -1)/2` is also just an expression that contains nothing but literals. This is evaluated at compile time and replaced with a single integer value. No calculation happening at runtime. – Damon Dec 07 '12 at 14:56