bradleykins
bradleykins

Reputation: 97

How to generate a new int with a specific amount of bits in it

The Problem

Hi there, i recently moved to using a binary representation for a domain in my program, this enhanced the speed of calculations with that domain, but i now need a method of generating ints based on an input number of bits needed.

My application is in Java so any code for that would be awesome.

Example

For example if i got the following input i would expect the following numbers:

User Input - Generated Int (binary of generated int)

01 - 1    (0b1)
02 - 3    (0b11)
03 - 7    (0b111)
04 - 15   (0b1111)
05 - 31   (0b11111)
06 - 63   (0b111111)
07 - 127  (0b1111111)
08 - 255  (0b11111111)
09 - 511  (0b111111111)
10 - 1023 (0b1111111111)

ETC

Any help would be useful thanks!

Upvotes: 1

Views: 310

Answers (2)

maskacovnik
maskacovnik

Reputation: 3084

Do you mean something like this:

public int getInt(int input){
    return (1<<input)-1;
}

Lets say input=5 then
1<<input (1<<5) is binary 100000
Then it needs to decrease only to 11111
its 31 in decimal

Upvotes: 5

bradleykins
bradleykins

Reputation: 97

Actually thought up the answer before i finished typing up and just tested it, might be useful for any other user who wants to know:

    int domain = 1;
    for (int x=0;x<USERINPUT;x++){
        domain = domain*2;
    }
    domain--;
    System.out.println("Domains:"+domain+" = "+Integer.toBinaryString(domain));

Upvotes: 0

Related Questions