byte[] Array to Integer

Status
Nicht offen für weitere Antworten.

MQue

Top Contributor
Hallo,

ich habe ein byte[] - Array in dem z.B.: steht:

Code:
[45, 50, 48, 48, 48, 13, 10]   // -2000 (nach ASCII)  13 und 10 sind CR und NL
oder
[48, 13, 10]                        // 0 (nach ASCII)

wie kann ich so ein byte- Array am schnellsten/besten in eine Integer- Zahl umwandeln?
Vielen Dank,
 
zb...

Java:
      byte[] arr = {45, 50, 48, 48, 48};

      String str = new String(arr);

      int i = Integer.valueOf(str);

      System.out.println(i);
 
Effizienter wäre es vermutlich mit bit-shifts - etwa wie
Code:
int i=0;
i |= ((arr[0]-'0') << 24);
i |= ((arr[1]-'0') << 16);
i |= ((arr[2]-'0') <<  8);
i |= ((arr[3]-'0') <<  0);
 
ich denke, das ist ein string der nur als byte[] vorliegt...

Java:
   public static void main(String[] args){
      byte[] arr = {50, 48, 48, 48};
      
      
      String str = new String(arr);
      int i = Integer.valueOf(str);
      System.out.println(i); //2000
      
      
      int x=0;
      x |= ((arr[0]-'0') << 24);
      x |= ((arr[1]-'0') << 16);
      x |= ((arr[2]-'0') <<  8);
      x |= ((arr[3]-'0') <<  0);

      System.out.println(x); //33554432

   }
 
Status
Nicht offen für weitere Antworten.

Zurück
Oben