byte數組轉換爲short,int

byte數組轉換爲short,int
int轉換爲byte數組
   private static byte[] shortToByteArray(short s) 
  {
   byte[] shortBuf = new byte[2];
   for(int i=0;i<2;i++)
   {
   int offset = (shortBuf.length - 1 -i)*8;
   shortBuf[i] = (byte)((s>>>offset)&0xff);
   }
   return shortBuf;
  }

   public static int byteArrayToShort(byte [] b) 
   {
    return (b[0] << 8)
            + (b[1] & 0xFF);
   }
   
   public static byte[] intToByteArray(int value)
   {
    byte[] b = new byte[4];
     for (int i = 0; i < 4; i++) 
     {
          int offset = (b.length - 1 - i) * 8;
          b[i] = (byte) ((value >>> offset) & 0xFF);
     }
     return b;
   }

  public static int byteArrayToInt(byte [] b) 
  {
           return (b[0] << 24)
                   + ((b[1] & 0xFF) << 16)
                   + ((b[2] & 0xFF) << 8)
                   + (b[3] & 0xFF);
  }

發佈了40 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章