關於byte 進位 float String 編碼 16進位字串轉16進位byte的問題__java代碼及演算法

來源:互聯網
上載者:User

首先 只有String才與編碼有關;

byte與其他類型轉換時,要注意大端點還是小端點,

編碼: Ascii Unicode gbk utf-8等等 

byte 占 8位 可由兩個16進位數(0xff)組成,一個16進位佔4位,也可由8位位元組成等等,與編碼沒關係,但可用2進位表示,也可由其他進位表示。

0xff”這樣的16進位字串轉換成16進位byte

String[] s="0X0C 0X03 0X00 0X04 0X00 0X02 0X84 0XD7".replace("X", "x").split(" ");byte[] b=new byte[s.length];for(int i=0;i<s.length;i++){b[i]=(byte)Integer.parseInt(s[i].substring(2),16);}System.out.println(Arrays.toString(b));


把byte[n]轉換成String;

new String(byte[n],0,length,"gbk");


float占 4位元組 ,float與byte類型轉換

都是通過移位來實現的

 4byte轉換成float

左移位
/**
* 位元組轉換為浮點

* @param b 位元組(至少4個位元組)
* @param index 開始位置
* @return
*/
public static float byte2float(byte[] b, int index) {  
   int l;                                           
   l = b[index + 0];                                
   l &= 0xff;                                       
   l |= ((long) b[index + 1] << 8);                 
   l &= 0xffff;                                     
   l |= ((long) b[index + 2] << 16);                
   l &= 0xffffff;                                   
   l |= ((long) b[index + 3] << 24);                
   return Float.intBitsToFloat(l);                  
}

  float轉換成4byte

   右移位 /**
 * 浮點轉換為位元組
 * 
 * @param f
 * @return
 */
public static byte[] float2byte(float f) {

// 把float轉換為byte[]
int fbit = Float.floatToIntBits(f);

byte[] b = new byte[4];  
    for (int i = 0; i < 4; i++) {  
        b[i] = (byte) (fbit >> (24 - i * 8));  
    } 
    
    // 翻轉數組
int len = b.length;
// 建立一個與源數組元素類型相同的數組
byte[] dest = new byte[len];
// 為了防止修改源數組,將源數組拷貝一份副本
System.arraycopy(b, 0, dest, 0, len);
byte temp;
// 將順位第i個與倒數第i個交換
for (int i = 0; i < len / 2; ++i) {
temp = dest[i];
dest[i] = dest[len - i - 1];
dest[len - i - 1] = temp;
}
    
    return dest;
    
}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.