3

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 .

Momo
  • 2,471
  • 5
  • 31
  • 52

6 Answers6

8

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;
}
Momo
  • 2,471
  • 5
  • 31
  • 52
6

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.

KeithS
  • 70,210
  • 21
  • 112
  • 164
4

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.

Adam Holmberg
  • 7,245
  • 3
  • 30
  • 53
0
public static String bytesToString(byte[] b) {
   try {
      return new String(b, "UTF-8");
   }

   catch (UnsupportedEncodingException ex) {
      Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
   }

   return null;
}

private int toInt(byte[] b1){
    String s1 = bytesToString(b1);
    int y = Integer.parseInt(s1);
    return y;
}

This code works perfectly, I was finding code example and nothing works, I do this.

0

I would recommend DatatypeConverter, it has multiple functions that can lead you to what you want

RicardoVallejo
  • 793
  • 7
  • 11
0

Looks like you forgot to shift left in the case where you're adding 256.

Also, you're assuming a little-endian byte[] (and you might want to validate that it's no more than 4 bytes long)

mpontillo
  • 13,559
  • 7
  • 62
  • 90