2
$\begingroup$

By writing out a number in binary I can arrive at the value of taking the first x number of bits out of it.

For example 00001101 (13) taking the first 6 bit would be 3
                          taking the first 5 bit would be 1
                          taking the first 4 bit would be 0 etc

This results, I can easily compute by spelling out the bits that makes up the number I am operating on, take the first couple of bits I am interested in and convert to binary.

I was wondering if there is any common short hand step which allows the same operation to be done, but in decimals (more like how we can do addition on decimals by carrying digits over) where I can use it to calculate what the result of taking the first x bits from a value y would be without having to mentally convert to a binary representation.

$\endgroup$
1
$\begingroup$

If your number $x$ is $n$ bit long, the number formed by the first $k$ is $x/2^{n-k}$, rounded down. The number formed by the last $k$ is the remainder in that division.

$\endgroup$
1
$\begingroup$

You should observe that the meaning of "the first six bits" depends on your assumptions. The binary numbers 0000 1101 and 0000 0000 0000 1101 are exactly the same, so their "first six bits" should be also the same - which means "first six bits" doesn't really make sense. What you actually mean is the bits from bit 2 to bit 7, with bit 0 being the bit with the lowest value.

Most programming languages have one or more "shift" operators which move bits into other positions, and bit operations like and, or, not, xor which perform common operations on bits.

And integers are not decimal or binary. Integers are integers. Decimal, binary, octal, hexadecimal, hexagesimal or whatever are just the way we write these numbers down.

$\endgroup$
  • $\begingroup$ It seems that the OP wants to do the calculation mentally rather than using a computer. $\endgroup$ – Yuval Filmus Aug 1 '16 at 8:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.