1

Possible Duplicate:
How do I convert Long to byte[] and back in java

I would like to convert a byte-value from specifical places in a byte-array (with offset of begin and how many bytes I would like to convert) in an int/long value? And if possible vice-versa, in case of int --> byte : 4bytes-array returned, and in case of long --> byte: 8bytes array returned?

I used the following methods, but they are returning false values..

public static final byte[] longToByteArray(long value) {
    return new byte[] {
            (byte)(value >>> 56),
            (byte)(value >>> 48),
            (byte)(value >>> 40),
            (byte)(value >>> 32),
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}


public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}


public static long byteToLongWert(byte[] array, int offBegin, int offEnd) 
{
    long result = 0;
    for (int i = offBegin; i<offEnd; i++) {
        result <<= 8; //verschieben um 8 bits nach links
        result += array[i];
    }
    return result;
}

public static int byteToIntWert(byte[] array, int offBegin, int offEnd) 
{
    int result = 0;
    for (int i = offBegin; i<offEnd; i++) {
        result <<= 8; //verschieben um 8 bits nach links
        result += array[i];
    }
    return result;
}

Thankyou verymuch for your help!!

Community
  • 1
  • 1
ZelelB
  • 1,836
  • 7
  • 45
  • 71

0 Answers0