久久96国产精品久久久-久久发布国产伦子伦精品-久久精品国产精品青草-久久天天躁夜夜躁狠狠85麻豆

技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機(jī)純凈版,64位旗艦版,綠色軟件,免費(fèi)軟件下載基地!

當(dāng)前位置:主頁(yè) > 教程 > 服務(wù)器類 >

Java字節(jié)流與基本數(shù)據(jù)類型的轉(zhuǎn)換實(shí)例教程

來(lái)源:技術(shù)員聯(lián)盟┆發(fā)布時(shí)間:2017-07-18 00:06┆點(diǎn)擊:

在實(shí)際開發(fā)中,我們經(jīng)常遇到與嵌入式進(jìn)行通信的情況,而由于一些嵌入式設(shè)備的處理能力較差,往往以二進(jìn)制的數(shù)據(jù)流的形式傳輸數(shù)據(jù),在此將這些常見的轉(zhuǎn)換做一總結(jié)。

注意:默認(rèn)傳輸時(shí)使用小端模式

將字節(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; }