负二进制转换java,Java的转换二进制负回整

I'm trying to convert an base 10 number to a base 2 and back to base 10. It works only for positive argument_decimal

argument_binary = Integer.toBinaryString(argument_decimal);

back_converted_argument_decimal = Integer.valueOf(argument_binary, 2);

For argument_decimal beeing negative, I get "java.lang.NumberFormatException: For input string: "11111111111111111111111111111111""

EDIT: here is what I do:

latitude_binary = Integer.toBinaryString((int)(latitude_decimal * 1000000));

back_converted_latitude_decimal = Long.parseLong(latitude_binary, 2) / 1000000.0;

which gives me bad results like -1.1 being forth and back converted to 4293.867296

解决方案

Try to go via a long:

String binary = Integer.toBinaryString(-1);

long l = Long.parseLong(binary, 2);

int i = (int) l;

Tested, and working.

Why this works is because -1 is represented as a sequence of 32 bits 1 in system memory. When using the toBinaryString method, it creates a string using that exact representation. But, 32 bits of one is in fact equal to 2^32 - 1. That is too large for an int (4 bytes), because an int goes from [-2^31, 2^31-1]. This is because the most left bit is representing the sign. So to fix that overflow, first interpret that sequence of 1 and 0 characters as a Long. A long will do because the maximum value for a long is 2^63-1. Then convert the long to an int. This is done by simply taking the lower 32 bits.

The bug in your code is that you didn't cast the Long.parseLong to an int. So this should work:

lat_bin = Integer.toBinaryString((int)(lat_dec * 1000000));

lat_dec_conv = ((int) Long.parseLong(lat_bin, 2)) / 1000000.0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值