Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get length of bits used in int

If you have the binary number 10110 how can I get it to return 11111? e.g a new binary number that sets all bits to 1 after the first 1, there are some likewise examples listed below:

101 should return 111 (3 bit length) 011 should return 11 (2 bit length) 11100 should be return 11111 (5 bit length) 101010101 should return 111111111 (9 bit length)

How can this be obtained the easiest way in Java? I could come up with some methods but they are not very "pretty".

like image 939
sigvardsen Avatar asked May 23 '10 13:05

sigvardsen


People also ask

How do you calculate bit length?

(bit length) = (propagation speed) × (bit duration) The bit duration is the inverse of the bandwidth. a. Bit length = (2 ×108 m) × [(1 / (1 Mbps)] = 200 m. This means a bit occupies 200 meters on a transmission medium.

How do you count the number of bits in an integer in Java?

Java Integer bitCount() method The bitCount() method of Integer class of java. lang package returns the count of the number of one-bits in the two's complement binary representation of an int value. This function is sometimes referred to as the population count.

How many bits are in a number?

Each digit in a binary number is called a bit. The number 1010110 is represented by 7 bits. Any number can be broken down this way, by finding all of the powers of 2 that add up to the number in question (in this case 26, 24, 22 and 21).


1 Answers

My try: Integer.highestOneBit(b) * 2 - 1

like image 111
hleinone Avatar answered Oct 17 '22 15:10

hleinone