Home > Blockchain >  Initialising an integer variable with a bit pattern
Initialising an integer variable with a bit pattern

Time:04-25

im an absolute beginner and have following task that I need to complete but im totally confused and can't find anything online, hope someone can help out.

Task:

Let the variable “pattern” be declared as an integer with 32 bits and initialised with the bit pattern 0011 1101 0101 1110 0101 1111 0001 1010 (3D5E 5F1A). Print the variable, set Bit 7 to 1 and print again.

Given:

int pattern = ;
boolean ww = false;
int value = 0;  
        
System.out.println("bitpattern = "   pattern   " --> "  Integer.toBinaryString(value));

When I understand that right, an integer is by default declared with 32bit so nothing to do for me for this part. But when I try to assign the number 0011 1101 0101 1110 0101 1111 0001 1010 to the "int pattern" I get the error "integer number too large".

where is my misconception ? Does anyone know a tutorial for that?

Thanks

CodePudding user response:

You can do it like this. The underscores are not required but make it easier to separate nibbles. Prefix the string with 0b.

int a = 0b0011_1101_0101_1110_0101_1111_0001_1010;
System.out.println(Integer.toHexString(a));

prints

3d5e5f1a

If you have a String of bits you can do

String bitStr = "00111101010111100101111100011010";
int v = Integer.parseInt(bitStr, 2);
System.out.println(Integer.toHexString(v));

prints

3d5e5f1a

For longs you must suffix with an L

long longbits = 0b0011110101011110010111110001101000111101010111100101111100011010L;

here are other prefixes available

int hex = 0x2A;  // prefix with 0x - 42 in decimal
int octal = 023  // prefix with 0 - 19 in decimal  

CodePudding user response:

If you had your input in string-form, you could use Integer.parse(input, 2) see docs.

In your case you could so that: value = Integer.parseInt(String.valueOf(pattern), 2) (enclosed in try catch)

  • Related