Java中數值類型與字節數組之間的轉換大法(精簡)


/**
* 整型轉字節數組
*
* @param data 待轉換數值
* @param bytes 轉換后的數組
* @param beginIndex 數組起始下標
* @return
*/
public static int int2Bytes(int data, byte[] bytes, int beginIndex) {
if (null == bytes || beginIndex < 0 || bytes.length < beginIndex + 4) {
return -1;
}

try {
bytes[beginIndex++] = (byte) (data & 0xff);
bytes[beginIndex++] = (byte) (data >> 8 & 0xff);
bytes[beginIndex++] = (byte) (data >> 16 & 0xff);
bytes[beginIndex++] = (byte) (data >> 24 & 0xff);
} catch (RuntimeException e) {
throw e;
}

return beginIndex;
}

/**
* 長整型轉字節數組
*
* @param data 待轉換數值
* @param bytes 轉換后的數組
* @param beginIndex 數組起始下標
* @return
*/
public static int long2Bytes(long data, byte[] bytes, int beginIndex) {
if (null == bytes || beginIndex < 0 || bytes.length < beginIndex + 8) {
return -1;
}

try {
bytes[beginIndex++] = (byte) (data & 0xff);
bytes[beginIndex++] = (byte) (data >> 8 & 0xff);
bytes[beginIndex++] = (byte) (data >> 16 & 0xff);
bytes[beginIndex++] = (byte) (data >> 24 & 0xff);
bytes[beginIndex++] = (byte) (data >> 32 & 0xff);
bytes[beginIndex++] = (byte) (data >> 40 & 0xff);
bytes[beginIndex++] = (byte) (data >> 48 & 0xff);
bytes[beginIndex++] = (byte) (data >> 56 & 0xff);
} catch (RuntimeException e) {
throw e;
}

return beginIndex;
}

/**
* 字節數組轉整型
*
* @param bytes 待轉換數組
* @param beginIndex 數組起始下標
* @return
*/
public static int bytes2Int(byte[] bytes, int beginIndex) {
if (null == bytes || beginIndex < 0 || bytes.length < beginIndex + 4) {
return -1;
}

int result = 0;
try {
int tmpVal = 0;
for (int i = 0; i < 4; i++) {
tmpVal = (bytes[i + beginIndex] << (i * 8));
switch (i) {
case 0:
tmpVal = tmpVal & 0x000000FF;
break;
case 1:
tmpVal = tmpVal & 0x0000FF00;
break;
case 2:
tmpVal = tmpVal & 0x00FF0000;
break;
case 3:
tmpVal = tmpVal & 0xFF000000;
break;
}

result |= tmpVal;
}
} catch (RuntimeException e) {
throw e;
}

return result;
}

/**
* 字節數組轉長整型
*
* @param bytes 待轉換數組
* @param beginIndex 數組起始下標
* @return
*/
public static long bytes2Long(byte[] bytes, int beginIndex) {
if (null == bytes || beginIndex < 0 || bytes.length < beginIndex + 8) {
return -1L;
}

long result = 0L;
try {
int shift = 0;
for (int i = 0; i < 8; i++) {
shift = i << 3;
result |= ((long) 0xff << shift) & ((long) bytes[i + beginIndex] << shift);
}
} catch (RuntimeException e) {
throw e;
}

return result;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM