Insert values from an array of bytes into an int array without converting them

Asked

Viewed 889 times

1

I have this vector int:

int[] vetor = new int [dataRegCodeToCompare.length];

and that byte vector : (which receives the "Digest" of another byte array)

byte[] dataRegCodeToCompare = md5.digest(toHash);

I want to put the byte array values dataRegCodeToCompare in the int array vetor. But without converting the values; for example in dataRegCodeToCompare[0]=12 then I want you to vetor[0]=dataRegCodeToCompare[0] which remains vetor[0]=12. That with all the values of array.

I can’t just do it vetor = dataRegCodeToCompare.

  • If I understand correctly do for(int i=0; i < dataRegCodeToCompare.length; i++){vetor[i] = dataRegCodeToCompare[i];}

  • That’s right @ramaral thank you so much!

1 answer

2

As far as I know, there is no ready-made Java function that allows you to do this in a row, perhaps because it is something relatively simple.

Just in case, I went to confirm Jon Skeet spoke on the subject, and at least in 2011 there was no.

You can implement it yourself:

public class ByteInt {
    public static void main(String[] args) {
        byte[] bytes = new byte[]{1, 2, 3, 4, (byte) 130}; //exemplo
        int[] sin = converteByteSinalizadoParaInt(bytes);
        int[] naoSin = converteByteNaoSinalizadoParaInt(bytes);

        System.out.println("Sinalizados");
        for(int s: sin) {
            System.out.println(s);
        }
        System.out.println("\nNão Sinalizados");
        for(int ns: naoSin) {
            System.out.println(ns);
        }
    }

    public static int[] converteByteSinalizadoParaInt(byte[] entrada) {
        int[] sin = new int[entrada.length];
        for(int i =0; i<entrada.length; i++) {
            sin[i] = entrada[i];                
        }
        return sin;
    }

    public static int[] converteByteNaoSinalizadoParaInt(byte[] entrada) {
        int[] naoSin = new int[entrada.length];
        for(int i =0; i<entrada.length; i++) {
            naoSin[i] = entrada[i] & 0xff;              
        }
        return naoSin;
    }
}

Exit:

Signposted
1
2
3
4
-126

Unmarked
1
2
3
4
130

Browser other questions tagged

You are not signed in. Login or sign up in order to post.