How to work with other base numbers in java?

Guys if int c = 10001; which is a binary value. If I want to process it, how to multiply it by 10, how to do it?

+6
java int
source share
5 answers

If I understand you correctly, you want to do this: Integer.parseInt("10001", 2) , which will give you 17.
Integer.toString also takes a radix value as the second argument.

Doc: Integer.parseInt (String s, int radix)

+15
source share

"int" is not binary, hexadecimal or decimal, it is just a place to store a number. The variables themselves do not have a specific representation of hex / dec / binary until you print them.

When you enter a number in your code, it has a base, but after it uses the base to process what you dialed, the base is discarded, and int just saves the number.

So the answer to your question is c * 10 (if you meant 10 dec)

+7
source share

You can specify it as int c = 0x11 (read 10001 0001 0001, which is 11 in hexadecimal format)

 public static void main(String[] args) throws Exception { int c = 0x11; // 10001 int d = 10; // ten decimal int d = 0x2; // ten binary 0010 - see table below System.out.println(c); System.out.println(c*d); System.out.println(c*e); } 

binary decimal conversion

  • 0 0000
  • 1 0001
  • 2,0010
  • 3 0011
  • 4 0100
  • 5 0101
  • 6 0110
  • 7 0111
  • 8 1000
  • 9 1001
  • A 1010
  • B 1011
  • C 1100
  • D 1101
  • E 1110
  • F 1111
+1
source share

Treatment

 int c = 10001; 

how a binary number is really strange. It would be better to declare it as String instead

 String binaryString = "10001"; 

and then loop each character to execute whatever basic transformation algorithm you want.

0
source share

Multiplication of a binary code with an integer:

  • If this is the power of two, then simply shift all the numbers to the exponents on the left
  • If this is not the power of two, find the largest power of the two less than the value you want to multiply by c. Do the same for the remainder and so on. In the end, just sum all the values.

For your example with c = 10001 (base 2) * 10 (base 10) this means (10 = 2 ^ 3 + 2 ^ 1)

 int c=10001 int result=c*1000+c*10 //left-shift 3 + left-shift 1 

But this is really not the best way to cope with such a task ... In addition, he considers it a bad idea to store a binary value in int. I think it would be better to convert the binary to an integer before using it.

0
source share

All Articles