Convert int and short to bytes : short « Data Type « Java






Convert int and short to bytes

     

public class Util{


  public static int bytesToInt(byte[] data) {
    int value=(data[3] & 0xff);
    value =value << 8;
    value|=(data[2] & 0xff);
    value <<= 8;
    value|=(data[1] & 0xff);
    value <<= 8;
    value|=(data[0] & 0xff);
    return value;
  }
  
  

  public static byte[] intTobytes(int value) {
    byte[] bytes = new byte[4];
    intTobytes(value, bytes);
    return bytes;
  }

  public static void intTobytes(int value, byte[] bytes) {
    bytes[3] = (byte) (value >> 24 & 0xff);
    bytes[2] = (byte) (value >> 16 & 0xff);
    bytes[1] = (byte) (value >> 8 & 0xff);
    bytes[0] = (byte) (value & 0xff);
  }
  
  public static void shortTobytes(short value, byte[] bytes) {
    bytes[1] = (byte) (value >> 8 & 0xff);
    bytes[0] = (byte) (value & 0xff);
  }
  
  
  public static short bytesToShort(byte[] data) {
    short value=(short) (data[1] & 0xff);
    value <<= 8;
    value|=(data[0] & 0xff);
    return value;
  }

}

   
    
    
    
    
  








Related examples in the same category

1.Java Short Example
2.Java short: short is 16 bit signed type ranges from –32,768 to 32,767.
3.Convert Java String to Short
4.Short class creates primitives that wrap themselves around data items of the short data type
5.Use toString method of Short class to convert Short into String.
6.Use Short constructor to convert short primitive type to Short object
7.short value
8.Convert Short to numeric primitive data types
9.Convert String to short primitive
10.Compare Two Java short Arrays
11.Java Sort short Array
12.Cast back to short
13.Cast result of plus operation to byte
14.Shorts Vs IntsShorts Vs Ints
15.Gets the maximum of three short values.
16.Gets the minimum of three short values.