In network programming, due to the need to save bandwidth or encoding, it is usually necessary to process long and int natively instead of converting to 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);// 最高位,無(wú)符號(hào)右移。 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,則將高位補(bǔ)0 } int v0 = (a[0] & 0xff) << 24;//&0xff將byte值無(wú)差異轉(zhuǎn)成int,避免Java自動(dòng)類型提升后,會(huì)保留高位的符號(hào)位 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; } }
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article
Guide: Stellar Blade Save File Location/Save File Lost/Not Saving
4 weeks ago
By DDD
Oguri Cap Build Guide | A Pretty Derby Musume
2 weeks ago
By Jack chen
Agnes Tachyon Build Guide | A Pretty Derby Musume
1 weeks ago
By Jack chen
Dune: Awakening - Advanced Planetologist Quest Walkthrough
4 weeks ago
By Jack chen
Date Everything: Dirk And Harper Relationship Guide
4 weeks ago
By Jack chen

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
