首頁 > Java > java教程 > 主體

Java位元組流與基本資料型別的轉換實例詳解

怪我咯
發布: 2017-07-02 10:18:38
原創
2386 人瀏覽過

本篇文章主要介紹了Java位元組流與基本資料型別的轉換實例,具有一定的參考價值,有興趣的小夥伴們可以參考一下

在實際開發中,我們經常遇到與嵌入式進行通信的情況,而由於一些嵌入式設備的處理能力較差,往往以二進制的數據流的形式傳輸數據,在此將這些常見的轉換做一總結。

注意:預設傳輸時使用小端模式

將位元組流轉換為int類型資料

public static int getInt(byte[] bytes) {
  return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & (bytes[2] << 16))
      | (0xff000000 & (bytes[3] << 24));
}
登入後複製

將位元組流轉換為long類型資料

public static long getLong(byte[] bytes) {
  return ((0xffL & (long) bytes[0]) | (0xff00L & ((long) bytes[1] << 8)) | (0xff0000L & ((long) bytes[2] << 16))
      | (0xff000000L & ((long) bytes[3] << 24)) | (0xff00000000L & ((long) bytes[4] << 32))
      | (0xff0000000000L & ((long) bytes[5] << 40)) | (0xff000000000000L & ((long) bytes[6] << 48))
      | (0xff00000000000000L & ((long) bytes[7] << 56)));
}
登入後複製

將位元組流轉換為float類型資料

public static float getFloat(byte[] bytes){
  int temp=getInt(bytes);
  return Float.intBitsToFloat(temp);
}
登入後複製

將位元組流轉換為

float

類型資料

public static double getDouble(byte[] bytes){
  long temp=getLong(bytes);
  return Double.longBitsToDouble(temp);
}
登入後複製

將位元組流轉換為double類型資料

public static byte[] getByteFromInt(int data){
  byte[] temp=new byte[4];
  temp[0]=(byte)(0xFF&(data));
  temp[1]=(byte)(0xFF&(data>>8));
  temp[2]=(byte)(0xFF&(data>>16));
  temp[3]=(byte)(0xFF&(data>>24));
  return temp;
}
登入後複製

將int類型資料轉換為位元組流

public static byte[] getByteFromLong(long data){
  byte[] temp=new byte[8];
  temp[0]=(byte)(0xFF&(data));
  temp[1]=(byte)(0xFF&(data>>8));
  temp[2]=(byte)(0xFF&(data>>16));
  temp[3]=(byte)(0xFF&(data>>24));
  temp[4]=(byte)(0xFF&(data>>32));
  temp[5]=(byte)(0xFF&(data>>40));
  temp[6]=(byte)(0xFF&(data>>48));
  temp[7]=(byte)(0xFF&(data>>56));
  return temp;
}
登入後複製

將long類型資料轉換為位元組流

public static byte[] getByteFromFloat(float data){
  byte[] temp=new byte[4];
  int tempInt=Float.floatToIntBits(data);
  temp[0]=(byte)(0xFF&(tempInt));
  temp[1]=(byte)(0xFF&(tempInt>>8));
  temp[2]=(byte)(0xFF&(tempInt>>16));
  temp[3]=(byte)(0xFF&(tempInt>>24));
  return temp;
}
登入後複製
###將float類型資料轉換為位元組流###
public static byte[] getByteFromDouble(double data){
  byte[] temp=new byte[8];
  long tempLong=Double.doubleToLongBits(data);
  temp[0]=(byte)(0xFF&(tempLong));
  temp[1]=(byte)(0xFF&(tempLong>>8));
  temp[2]=(byte)(0xFF&(tempLong>>16));
  temp[3]=(byte)(0xFF&(tempLong>>24));
  temp[4]=(byte)(0xFF&(tempLong>>32));
  temp[5]=(byte)(0xFF&(tempLong>>40));
  temp[6]=(byte)(0xFF&(tempLong>>48));
  temp[7]=(byte)(0xFF&(tempLong>>56));
  return temp;
}
登入後複製
###將double類型資料轉換為位元組流###rrreee

以上是Java位元組流與基本資料型別的轉換實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!