Best practice for getting datatype size(sizeof) in Java

前端 未结 7 1653
感情败类
感情败类 2021-02-01 03:53

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*size         


        
7条回答
  •  死守一世寂寞
    2021-02-01 04:19

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

提交回复
热议问题