Boa tarde galera estou com uma duvida na conversão de bytes para int;
int val = 475;
byte[] bytes = new byte[2];
//Converto o numero 475 em bytes
bytes[0] = (byte) ( val / 256); // Igual a 1;
bytes[1] = (byte) (val - bytes[0] * 256); // igual a -37
//mas quando vou transformar de volta em int da errado
val = bytes[0] * 256 + bytes[1] // está resultando em 219
Será que alguém pode me ajudar neste calculo?
Em Java um int
ocupa 4 bytes, então você deveria armazená-lo em um array de 4 bytes, pra evitar de truncar o valor.
byte[] intToBytes(int value) {
return new byte[] {
(byte) (0xff & (value >> 24)),
(byte) (0xff & (value >> 16)),
(byte) (0xff & (value >> 8)),
(byte) (0xff & value)
};
}
int bytesToInt(byte[] bytes) {
return ((bytes[0] & 0xff) << 24)
| ((bytes[1] & 0xff) << 16)
| ((bytes[2] & 0xff) << 8)
| (bytes[3] & 0xff));
}