how to work with other base numbers in java?

前端 未结 5 1988
广开言路
广开言路 2021-01-05 11:13

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

5条回答
  •  猫巷女王i
    2021-01-05 11:44

    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.

提交回复
热议问题