Convert Byte[] to int

42,894

Solution 1

Thank you for the answers but I found that the problem comes from somewhere else, not from the conversion methode,

there is an other version of the methode

public int convertirOctetEnEntier(byte[] b){    
    int MASK = 0xFF;
    int result = 0;   
        result = b[0] & MASK;
        result = result + ((b[1] & MASK) << 8);
        result = result + ((b[2] & MASK) << 16);
        result = result + ((b[3] & MASK) << 24);            
    return result;
}

Solution 2

OK, so you have a big-endian byte array that you are converting to an int. I don't think it matters what the value of each byte is; you just need to stick them all together:

public int convertByteToInt(byte[] b)
{           
    int value= 0;
    for(int i=0; i<b.length; i++)
       value = (value << 8) | b[i];     
    return value;       
}

If I'm missing something here, let me know.

Solution 3

Are you writing the code as an exercise, or are you just looking for a way to do it? If the latter, I would suggest using ByteBuffer. It has a getInt method that should do the trick.

Share:
42,894
Momo
Author by

Momo

Updated on May 26, 2020

Comments

  • Momo
    Momo almost 4 years

    I have this method that converts a signed or non-signed byte to int, but it doesn't return what it is supposed to return. Can someone point out the issue in the below code?

    public int convertByteToInt(byte[] b){          
        int value= 0;
        for(int i=0;i<b.length;i++){                
        int n=(b[i]<0?(int)b[i]+256:(int)b[i])<<(8*i);             
            value+=n;
        }         
        return value;       
    }
    

    Edited :

    I'am actualy reading a wav file in order to calculate the SNR. the returned value from the conversion should give something beetween 0 and 255. The application should compare 2 waves file, on is the orignal one and the other is modified and calculate the SNR .