开发者

how to work with other base numbers in java?

Guys if the int c=10001; which is a binary value.If i开发者_C百科 want to process it like multiplying it by 10 how to do that?


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

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


an "int" is neither binary, hex or decimal, it's just a place to store a number. Variables themselves don't have a specific hex/dec/binary representation until you print them.

When you type the number into your code it has a base, but after it uses the base to process what you typed, the base is thrown away and the int just stores a number.

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


You can specify it as int c = 0x11 (consider 10001 is 0001 0001, which is 11 in hex)

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


Treating

int c = 10001;

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

String binaryString = "10001";

and then looping through each character to perform whatever base conversion algorithm you want.


The multiplication of a binary with an integer:

  • If it's a power of two, then just left-shift all digits to the exponents value left
  • If it's not a power of two find the biggest power of two smaller then the value you want to multiply your c with. The do the same for the remainder and so on. At the end just sum up all 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 a good way to handle this kind of task... Moreover it think it's a bad idea to save an binary value into an int. I think it would be better to convert the binary into an integer before using it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜