在網(wǎng)絡(luò)編程中,出于節(jié)約帶寬或者編碼的需要,通常需要以原生方式處理long和int,而不是轉(zhuǎn)換為string。
public class ByteOrderUtils { public static byte[] int2byte(int res) { byte[] targets = new byte[4]; targets[3] = (byte) (res & 0xff);// 最低位 targets[2] = (byte) ((res >> 8) & 0xff);// 次低位 targets[1] = (byte) ((res >> 16) & 0xff);// 次高位 targets[0] = (byte) (res >>> 24);// 最高位,無符號右移。 return targets; } public static int byteArrayToInt(byte[] b){ byte[] a = new byte[4]; int i = a.length - 1,j = b.length - 1; for (; i >= 0 ; i--,j--) {//從b的尾部(即int值的低位)開始copy數(shù)據(jù) if(j >= 0) a[i] = b[j]; else a[i] = 0;//如果b.length不足4,則將高位補0 } int v0 = (a[0] & 0xff) << 24;//&0xff將byte值無差異轉(zhuǎn)成int,避免Java自動類型提升后,會保留高位的符號位 int v1 = (a[1] & 0xff) << 16; int v2 = (a[2] & 0xff) << 8; int v3 = (a[3] & 0xff) ; return v0 + v1 + v2 + v3; } public static byte[] long2byte(long res) { byte[] buffer = new byte[8]; for (int i = 0; i < 8; i++) { int offset = 64 - (i + 1) * 8; buffer[i] = (byte) ((res >> offset) & 0xff); } return buffer; } public static long byteArrayToLong(byte[] b){ long values = 0; for (int i = 0; i < 8; i++) { values <<= 8; values|= (b[i] & 0xff); } return values; } }
本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔相應(yīng)法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool
免費脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機

Video Face Swap
使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章
指南:恒星刀片保存文件位置/保存文件丟失/不保存
4 周前
By DDD
Agnes Tachyon Build Guide |漂亮的德比志
2 周前
By Jack chen
Oguri Cap Build Guide |漂亮的德比志
2 周前
By Jack chen
沙丘:覺醒 - 高級行星學(xué)家Quest演練
4 周前
By Jack chen
約會一切:德克和哈珀關(guān)系指南
4 周前
By Jack chen

熱工具

記事本++7.3.1
好用且免費的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級代碼編輯軟件(SublimeText3)