Java字節(jié)流與基本數(shù)據(jù)類型的轉(zhuǎn)換實例
在實際開發(fā)中,我們經(jīng)常遇到與嵌入式進行通信的情況,而由于一些嵌入式設備的處理能力較差,往往以二進制的數(shù)據(jù)流的形式傳輸數(shù)據(jù),在此將這些常見的轉(zhuǎn)換做一總結(jié)。
注意:默認傳輸時使用小端模式
將字節(jié)流轉(zhuǎn)換為int類型數(shù)據(jù)
public static int getInt(byte[] bytes) {
return (0xff & bytes[0]) | (0xff00 & (bytes[1] << 8)) | (0xff0000 & (bytes[2] << 16))
| (0xff000000 & (bytes[3] << 24));
}
將字節(jié)流轉(zhuǎn)換為long類型數(shù)據(jù)
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)));
}
將字節(jié)流轉(zhuǎn)換為float類型數(shù)據(jù)
public static float getFloat(byte[] bytes){
int temp=getInt(bytes);
return Float.intBitsToFloat(temp);
}
將字節(jié)流轉(zhuǎn)換為double類型數(shù)據(jù)
public static double getDouble(byte[] bytes){
long temp=getLong(bytes);
return Double.longBitsToDouble(temp);
}
將int類型數(shù)據(jù)轉(zhuǎn)換為字節(jié)流
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;
}
將long類型數(shù)據(jù)轉(zhuǎn)換為字節(jié)流
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;
}
將float類型數(shù)據(jù)轉(zhuǎn)換為字節(jié)流
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;
}
將double類型數(shù)據(jù)轉(zhuǎn)換為字節(jié)流
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;
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java+Eclipse+Selenium環(huán)境搭建的方法步驟
這篇文章主要介紹了Java+Eclipse+Selenium環(huán)境搭建的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06
java eclipse 整個項目或包查找只定字符串并替換操作
這篇文章主要介紹了java eclipse 整個項目或包查找只定字符串并替換操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Java設計模式之解釋器模式_動力節(jié)點Java學院整理
解釋器模式是一個比較少用的模式,本人之前也沒有用過這個模式。下面我們就來一起看一下解釋器模式2017-08-08

