Mar*_*tin 4 java unsigned signed byte
我想转换一个java.net.InetAddress和我签署/签署的问题.这样的痛苦.
我在Java中读取从短到字节的转换,反之亦然,为什么字节b =(字节)0xFF等于整数-1?
结果得出:
final byte [] pumpeIPAddressRaw =
java.net.InetAddress.getByName (pumpeIPAddressName).getAddress ();
final long pumpeIPAddress =
((pumpeIPAddressRaw [0] & 0xFF) << (3*8)) +
((pumpeIPAddressRaw [1] & 0xFF) << (2*8)) +
((pumpeIPAddressRaw [2] & 0xFF) << (1*8)) +
(pumpeIPAddressRaw [3] & 0xFF);
android.util.Log.i (
Application.TAG, "LOG00120: Setzte Pumpen Addresse : " +
pumpeIPAddress + ":" + pumpeIPPort);
Run Code Online (Sandbox Code Playgroud)
并猜猜日志仍然显示:
04-10 13:12:07.398 I/ch.XXXX.remote.Application(24452): LOG00120: Setzte Pumpen Addresse : -1063035647:27015
Run Code Online (Sandbox Code Playgroud)
有人知道我还在做错吗?
& 0xff块转换过程中从符号扩展byte到int,但你的表达也包含从转换int到long你需要阻止这个转换过程中符号扩展,以及:
final long pumpeIPAddress =
(((pumpeIPAddressRaw [0] & 0xFF) << (3*8)) +
((pumpeIPAddressRaw [1] & 0xFF) << (2*8)) +
((pumpeIPAddressRaw [2] & 0xFF) << (1*8)) +
(pumpeIPAddressRaw [3] & 0xFF)) & 0xffffffffl;
Run Code Online (Sandbox Code Playgroud)
或者,可以从转换byte到long在一个单一的步骤中,通过标记的第二操作数& 0xff的操作,long使用l后缀:
final long pumpeIPAddress =
((pumpeIPAddressRaw [0] & 0xFFl) << (3*8)) +
((pumpeIPAddressRaw [1] & 0xFFl) << (2*8)) +
((pumpeIPAddressRaw [2] & 0xFFl) << (1*8)) +
(pumpeIPAddressRaw [3] & 0xFFl);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4198 次 |
| 最近记录: |