Best practice for getting datatype size(sizeof) in Java

倾然丶 夕夏残阳落幕 提交于 2019-12-03 04:52:32

问题


I want store a list of doubles and ints to a ByteBuffer, which asks for a size to allocate. I'd like to write something like C's syntax

int size=numDouble*sizeof(double)+numInt*sizeof(int);

But there is no sizeof in Java. What is the best practice to calculate the size in byte? Should I hardcode it?


回答1:


(If you're using Java 8 or beyond, be sure to look at @Frank Kusters' answer!)

All of the primitive wrappers have a SIZE constant, which is in bits, not bytes.

So in the example given, it would be:

int size=(numDouble*Double.SIZE+numInt*Integer.SIZE) / Byte.SIZE;

Or, if you wanted to avoid the division:

int size=numDouble*(Double.SIZE/Byte.SIZE)+numInt*(Integer.SIZE/Byte.SIZE);

(Because the division is of two constants, it's done at compile-time.)




回答2:


Since Java 8, all wrapper classes of primitive types (except Boolean) have a BYTES field. So in your case:

int size = numDouble * Double.BYTES + numInt * Integer.BYTES;

Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html




回答3:


Write your own method. In Java the datatypes are platform independent always the same size:

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

Usage:

int size = numDouble * sizeof(double.class) + numInt * sizeof(int.class);



回答4:


A better solution might be to not emulate C syntax and use an ObjectOutputStream with a nested ByteArrayOutputStream to generate a byte array which can then be written to your ByteBuffer.




回答5:


The size in Java is always the same. You can hardcode it but you only need to do this because you are working with bytes in a ByteBuffer. If you use double[] or DoubleBuffer you don't need these.




回答6:


You can also use the sizeof4j library to get the sizeof the double you just need SizeOf.doubleSize()



来源:https://stackoverflow.com/questions/6766343/best-practice-for-getting-datatype-sizesizeof-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!