Primitive casting or byte trimming

I would like to ask for opinions / advice regarding part of my algorithm.

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);

against.

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);

Basically, I would like to know if there is a difference in casting performance or is it better to use a larger ByteBuffer.

Thanks Hi,

Marek

+3
source share
1 answer

Basically, I would like to know if there is a difference in casting performance or is it better to use a larger ByteBuffer.

Casting is “cheap” especially compared to distributing new ByteBufferand calling several methods.

I'm not quite sure what you are trying to do, but maybe a simple transition-right will do the trick? For example, this piece of code:

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)});
+3
source

Source: https://habr.com/ru/post/1791226/


All Articles