我想将双精度和整数的列表存储到ByteBuffer,后者要求分配大小。我想写一些类似C的语法
int size=numDouble*sizeof(double)+numInt*sizeof(int);
但是Java中没有sizeof
。计算字节大小的最佳实践是什么?我应该对其进行硬编码吗?
请参见下面的@Frank Kusters' answer!
(我的原始答案是针对Java版本<8。]
自Java 8起,所有原始类型的包装器类(Boolean
除外)都具有BYTES
字段。因此,在您的情况下:
int size = numDouble * Double.BYTES + numInt * Integer.BYTES;
文档:http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html
编写您自己的方法。在Java中,数据类型与平台无关,并且大小始终相同:
public static int sizeof(Class dataType)
{
if (dataType == null) throw new NullPointerException();
if (dataType == int.class || dataType == Integer.class) return 4;
if (dataType == short.class || dataType == Short.class) return 2;
if (dataType == byte.class || dataType == Byte.class) return 1;
if (dataType == char.class || dataType == Character.class) return 2;
if (dataType == long.class || dataType == Long.class) return 8;
if (dataType == float.class || dataType == Float.class) return 4;
if (dataType == double.class || dataType == Double.class) return 8;
return 4; // 32-bit memory pointer...
// (I'm not sure how this works on a 64-bit OS)
}
用法:
int size = numDouble * sizeof(double.class) + numInt * sizeof(int.class);
更好的解决方案可能是不模拟C语法,并使用带有嵌套ByteArrayOutputStream的ObjectOutputStream生成字节数组,然后可以将其写入您的ByteBuffer。
Java中的大小始终相同。您可以对其进行硬编码,但只需要这样做,因为您正在使用ByteBuffer中的字节。如果使用double[]
或DoubleBuffer
,则不需要这些。
您也可以使用sizeof4j库来获取只需要SizeOf.doubleSize()
的两倍的大小>
自动和抽象的解决方案是将示例写入DataOutput并查看结果大小。