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++.

4
  • 3
    << and >> and | and &. Commented Dec 7, 2012 at 14:43
  • 4
    Any decent compiler would optimize x / 2. See this question or this one or this other one. Commented Dec 7, 2012 at 14:43
  • 1
    If one bit shift divides by 2 (2^1), then three bit shifts divides by ? Commented Dec 7, 2012 at 14:43
  • 1
    Google "c++ bit manipulation" and you'll find many tutorials. Commented Dec 7, 2012 at 14:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What do you mean, how will the compiler know to optimize "int x = 256/8;"
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.
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"
(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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.