Android Byte Array to Double Convert toDouble(byte[] b, int pos, int width)

Here you can find the source of toDouble(byte[] b, int pos, int width)

Description

to Double

Declaration

public static double toDouble(byte[] b, int pos, int width) 

Method Source Code

//package com.java2s;

public class Main {

    public static double toDouble(byte[] b, int pos) {
        long l;//from ww w . j av a2  s. co  m

        l = b[pos];
        l &= 0xff;
        l |= ((long) b[pos + 1] << 8);
        l &= 0xffff;
        l |= ((long) b[pos + 2] << 16);
        l &= 0xffffff;
        l |= ((long) b[pos + 3] << 24);
        l &= 0xffffffffl;
        l |= ((long) b[pos + 4] << 32);
        l &= 0xffffffffffl;

        l |= ((long) b[pos + 5] << 40);
        l &= 0xffffffffffffl;
        l |= ((long) b[pos + 6] << 48);

        l |= ((long) b[pos + 7] << 56);
        return Double.longBitsToDouble(l);
    }

    public static double toDouble(byte[] b, int pos, int width) {
        double retVal = Double.MAX_VALUE;
        switch (width) {
        case 1:
        case 2:
        case 4:
            return (double) toInteger(b, pos, width);
        case 8:
            return toDouble(b, pos);
        default:
            break;
        }
        return retVal;
    }

    public static int toInteger(byte[] b, int pos) {
        int ret = 0;
        for (int i = 0; i < 4; i++) {
            ret |= (b[i + pos] & 0xFF) << (8 * i);
        }
        return ret;
    }

    public static int toInteger(byte[] b, int pos, int width) {
        int retVal = Integer.MAX_VALUE;
        switch (width) {
        case 1:
            retVal = b[pos];
            if (retVal < 0) {
                retVal &= 0x000000FF;
            }
            break;
        case 2:
            retVal = toIntFromTwoBytes(b, pos);
            break;
        case 4:
            retVal = toInteger(b, pos);
            break;
        default:
            break;
        }

        return retVal;
    }

    public static int toIntFromTwoBytes(byte[] b, int pos) {
        int ret = 0;
        ret |= (b[pos] & 0xFF);
        ret |= (b[pos + 1] & 0xFF) << 8;

        return (int) ret;
    }
}

Related

  1. bytesLE2doubles(byte[] b)
  2. getDouble(byte[] b, int index)
  3. getDouble(byte[] buf, boolean bigEndian)
  4. getDouble(byte[] bytes)
  5. toDouble(byte[] b, int pos)
  6. byteToDouble(byte[] b)
  7. convertByteArrayToDoubleArray(byte[] bytes)