编程语言
首页 > 编程语言> > java-铸造基本对象与按字节修剪

java-铸造基本对象与按字节修剪

作者:互联网

我想征求有关我算法一部分的意见/建议.

ByteBuffer bb = ByteBuffer.allocate(8);
bb.putLong(rs.getLong(index));//retrieve long from db (unsigned INT)
byte[] tmp = new byte[4];
bb.position(4);
bb.get(tmp);
(Inet4Address) InetAddress.getByAddress(tmp);

ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt((int) rs.getLong(index));//retrieve long from db (unsigned INT)
bb.flip();
byte[] tmp = new byte[4];
bb.get(tmp);
(Inet4Address) InetAddress.getByAddress(tmp);

基本上,我想知道转换是否存在性能差异,还是使用更大的ByteBuffer更好.

感谢和问候,

马雷克

解决方法:

Basically I would like to know whether there is a performance difference in casting or is it better to use bigger ByteBuffer.

与分配新的ByteBuffer和调用一些方法相比,转换是“便宜的”.

我不确定您要做什么,但也许简单的右移就可以解决问题?例如下面的代码片段:

long l = rs.getLong(index);
InetAddress.getByAddress(new byte[] { (byte) ((l & 0xFF000000) >> 24),
                                      (byte) ((l & 0x00FF0000) >> 16),
                                      (byte) ((l & 0x0000FF00) >>  8),
                                      (byte) ((l & 0x000000FF) >>  0)});

标签:bytebuffer,casting,ipv4,java
来源: https://codeday.me/bug/20191208/2093646.html