# Quick way to do bit AND mapping

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.

## 2 Answers

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.

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.

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