2012-04-18 137 views
0

我有一個字節數組,我想將它們轉換爲整數。 如何做到這一點? 如下我的代碼:轉換字節數組爲整數

byte[] bytes = new byte[]{(byte)0xFF, (byte)0x01, (byte)0x0F, ...}; 
int[] integers = new int[bytes.length]; 
int i; 
for(i = 0; i < bytes.length; i++) { 
integers[i] = bytes[i]; 
} 

獲取到整數數組爲{-1,1,15,...}。 但我想得到的是{255,1,15,...}。 任何函數都可以抵達嗎?

+0

您可以添加256爲負值[字節數組unsigned int類型在Java]的 – Attila 2012-04-18 02:16:22

+0

可能重複(HTTP:/ /stackoverflow.com/questions/1576374/byte-array-to-unsigned-int-in-java) – 2012-04-18 02:32:54

+0

@KshitijMehta:這甚至不是一樣的東西。 – Ryan 2012-04-18 02:36:58

回答

3

嘗試:

integers[i] = (int)bytes[i] & 0xff; 
-1

整數[I] =(uint8_t)(字節[I] & 0xff的);

會讓你255而不是-1。 〜本

+1

這個問題問java關於java不作爲uint8_t在java中不存在AFAIK – 2012-04-18 02:24:14

+0

哦好打電話,不知道java足夠好〜本 – Ben 2012-04-18 19:08:14

2

我創造了這個類爲我個人使用,但我認爲它可以幫助你解決你的問題。

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

import java.lang.reflect.Array; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 
import java.util.HashMap; 
import java.util.Map; 

public class ArrayUtils { 

    private static final Logger log = LoggerFactory.getLogger(ArrayUtils.class); 
    private static final Map<Class, Class> primitiveMapping = new HashMap<Class, Class>(); 
    private static final Map<Class, Method> primitiveParseMethodLookup = new HashMap<Class, Method>(); 
    private static final Map<Class, Method> primitiveArrayGetMethodLookup = new HashMap<Class, Method>(); 
    private static final Map<Class, Method> valueOfMethodLookup = new HashMap<Class, Method>(); 

    static { 

     // Initialize primitive mappings 
     primitiveMapping.put(boolean.class, Boolean.class); 
     primitiveMapping.put(byte.class, Byte.class); 
     primitiveMapping.put(short.class, Short.class); 
     primitiveMapping.put(int.class, Integer.class); 
     primitiveMapping.put(float.class, Float.class); 
     primitiveMapping.put(long.class, Long.class); 
     primitiveMapping.put(double.class, Double.class); 

     // Initialize parse, valueOf and get method lookup 
     // We do that in advance because the lookup of the method takes the longest time 
     // Compared to the normal method call it's 20x higher 
     // So we use just the reflective method call which takes double the time of a normal method call 
     try { 
      primitiveParseMethodLookup.put(boolean.class, Boolean.class.getMethod("parseBoolean", new Class[]{String.class})); 
      primitiveParseMethodLookup.put(byte.class, Byte.class.getMethod("parseByte", new Class[]{String.class})); 
      primitiveParseMethodLookup.put(short.class, Short.class.getMethod("parseShort", new Class[]{String.class})); 
      primitiveParseMethodLookup.put(int.class, Integer.class.getMethod("parseInt", String.class)); 
      primitiveParseMethodLookup.put(float.class, Float.class.getMethod("parseFloat", String.class)); 
      primitiveParseMethodLookup.put(long.class, Long.class.getMethod("parseLong", String.class)); 
      primitiveParseMethodLookup.put(double.class, Double.class.getMethod("parseDouble", String.class)); 

      valueOfMethodLookup.put(Boolean.class, Boolean.class.getMethod("valueOf", new Class[]{String.class})); 
      valueOfMethodLookup.put(Byte.class, Byte.class.getMethod("valueOf", new Class[]{String.class})); 
      valueOfMethodLookup.put(Short.class, Short.class.getMethod("valueOf", new Class[]{String.class})); 
      valueOfMethodLookup.put(Integer.class, Integer.class.getMethod("valueOf", String.class)); 
      valueOfMethodLookup.put(Float.class, Float.class.getMethod("valueOf", String.class)); 
      valueOfMethodLookup.put(Long.class, Long.class.getMethod("valueOf", String.class)); 
      valueOfMethodLookup.put(Double.class, Double.class.getMethod("valueOf", String.class)); 

      primitiveArrayGetMethodLookup.put(boolean.class, Array.class.getMethod("getBoolean", new Class[]{Object.class, int.class})); 
      primitiveArrayGetMethodLookup.put(byte.class, Array.class.getMethod("getByte", new Class[]{Object.class, int.class})); 
      primitiveArrayGetMethodLookup.put(short.class, Array.class.getMethod("getShort", new Class[]{Object.class, int.class})); 
      primitiveArrayGetMethodLookup.put(int.class, Array.class.getMethod("getInt", Object.class, int.class)); 
      primitiveArrayGetMethodLookup.put(float.class, Array.class.getMethod("getFloat", Object.class, int.class)); 
      primitiveArrayGetMethodLookup.put(long.class, Array.class.getMethod("getLong", Object.class, int.class)); 
      primitiveArrayGetMethodLookup.put(double.class, Array.class.getMethod("getDouble", Object.class, int.class)); 
     } catch (NoSuchMethodException e) { 

      //****************************** 
      // This can never happen 
      //****************************** 
     } 

    } 

    public static boolean isArrayOfPrimitives(Object object) { 

     if (object.getClass().isArray()) { 
      return object.getClass().getComponentType().isPrimitive(); 
     } 

     return false; 
    } 

    public static boolean isArrayOf(Object object, Class clazz) { 

     if (object.getClass().isArray()) { 
      return clazz.isAssignableFrom(object.getClass().getComponentType()); 
     } 

     return false; 
    } 

    /** 
    * Convert any array of primitives(excluding char), strings or numbers into any other array 
    * of strings or numbers. 
    * 
    * @param array      Array of primitives(excluding char), strings or numbers 
    * @param convertedArrayComponentType Converted array component type (String or Number) 
    * @param <T>       To allow implicit casting 
    * @return Array of convertedArrayComponentType 
    */ 
    public static <T> T[] convertArray(Object array, Class<T> convertedArrayComponentType) { 

     // Collect data regarding arguments 
     final boolean arrayOfPrimitives = isArrayOfPrimitives(array); 
     final boolean arrayOfCharPrimitives = isArrayOf(array, char.class); 
     final boolean arrayOfCharacters = isArrayOf(array, Character.class); 
     final boolean arrayOfStrings = isArrayOf(array, String.class); 
     final boolean arrayOfNumbers = isArrayOf(array, Number.class); 

     // Check if array is an array of strings, primitives or wrapped primitives 
     if (!arrayOfPrimitives && !arrayOfNumbers && !arrayOfStrings || arrayOfCharPrimitives || arrayOfCharacters) { 
      throw new IllegalArgumentException(array + " must be an array of of strings, primitives or boxed primitives (byte, boolean, short, int, float, long, double)"); 
     } 

     // Check if it's assignable from Number of String 
     if (!Number.class.isAssignableFrom(convertedArrayComponentType) && !String.class.isAssignableFrom(convertedArrayComponentType)) { 
      throw new IllegalArgumentException(convertedArrayComponentType + " must be a Number or a String"); 
     } 

     try { 
      return (T[]) convertArrayInternal(array, convertedArrayComponentType); 
     } catch (InvocationTargetException e) { 

      // This can happen due to errors in conversion 
      throw (RuntimeException) e.getTargetException(); 
     } catch (Exception e) { 

      // This should never happen 
      log.error("Something went really wrong in ArrayUtils.convertArray method.", e); 
     } 

     // To satisfy the compiler 
     return null; 
    } 

    /** 
    * Convert any array of primitives(excluding char), strings or numbers into an array 
    * of primitives(excluding char). 
    * 
    * @param array      Array of primitives(excluding char), strings or numbers 
    * @param convertedArrayComponentType Converted array component type primitive(excluding char) 
    * @return Array of convertedArrayComponentType 
    */ 
    public static Object convertToPrimitiveArray(Object array, Class convertedArrayComponentType) { 

     // Collect data regarding arguments 
     final boolean arrayOfPrimitives = isArrayOfPrimitives(array); 
     final boolean arrayOfCharPrimitives = isArrayOf(array, char.class); 
     final boolean arrayOfCharacters = isArrayOf(array, Character.class); 
     final boolean arrayOfStrings = isArrayOf(array, String.class); 
     final boolean arrayOfNumbers = isArrayOf(array, Number.class); 

     // Check if array is an array of strings, primitives or wrapped primitives 
     if (!arrayOfPrimitives && !arrayOfNumbers && !arrayOfStrings || arrayOfCharPrimitives || arrayOfCharacters) { 
      throw new IllegalArgumentException(array + " must be an array of of strings, primitives or boxed primitives (byte, boolean, short, int, float, long, double)"); 
     } 

     // Check if it's assignable from Number of String 
     if (!convertedArrayComponentType.isPrimitive() || convertedArrayComponentType.isAssignableFrom(char.class)) { 
      throw new IllegalArgumentException(convertedArrayComponentType + " must be a primitive(excluding char)"); 
     } 

     try { 
      return convertArrayInternal(array, convertedArrayComponentType); 
     } catch (InvocationTargetException e) { 

      // This can happen due to errors in conversion 
      throw (RuntimeException) e.getTargetException(); 
     } catch (Exception e) { 

      // This should never happen 
      log.error("Something went really wrong in ArrayUtils.convertArray method.", e); 
     } 

     // To satisfy the compiler 
     return null; 
    } 

    private static Object convertArrayInternal(Object array, Class convertedArrayComponentType) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { 

     // Lookup the primitive parse method or the boxed primitive valueOf method 
     final Method convertMethod; 
     if (convertedArrayComponentType.isPrimitive()) { 
      convertMethod = primitiveParseMethodLookup.get(convertedArrayComponentType); 
     } else { 
      convertMethod = valueOfMethodLookup.get(convertedArrayComponentType); 
     } 

     // If the array is an array of primitives lookup the get method 
     final Method primitiveArrayGetMethod = primitiveArrayGetMethodLookup.get(array.getClass().getComponentType()); 

     // Get length and create new array 
     final int arrayLength = Array.getLength(array); 
     final Object castedArray = Array.newInstance(convertedArrayComponentType, arrayLength); 

     for (int i = 0; i < arrayLength; i++) { 

      final Object value; 
      if (primitiveArrayGetMethod != null) { 
       value = primitiveArrayGetMethod.invoke(null, array, i); 
      } else { 
       value = Array.get(array, i); 
      } 

      final String stringValue = String.valueOf(value); 
      final Object castedValue = convertMethod.invoke(null, stringValue); 
      Array.set(castedArray, i, castedValue); 
     } 

     return castedArray; 
    } 

} 

你不能在java中這樣做,因爲類型都是有符號的。 一個字節可以容納-128的值到127 爲了實現這一目標,您可以使用

short[] bytes = new short[]{(short)0xFF, (short)0x01, (short)0x0F}; 
Integer[] integers = ArrayUtils.convertArray(bytes, Integer.class); 
int[] ints = (int[]) ArrayUtils.convertToPrimitiveArray(bytes, int.class);