int与byte[]之间的转换

妖狐艹你老母 2022-02-19 15:23 323阅读 0赞

标题这里简单记录下两种转换方式:

标题第一种:

1、int与byte[]之间的转换(类似的byte short,long型)

  1. /**
  2. * 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。 和bytesToInt()配套使用
  3. * @param value
  4. * 要转换的int值
  5. * @return byte数组
  6. */
  7. public static byte[] intToBytes( int value )
  8. {
  9. byte[] src = new byte[4];
  10. src[3] = (byte) ((value>>24) & 0xFF);
  11. src[2] = (byte) ((value>>16) & 0xFF);
  12. src[1] = (byte) ((value>>8) & 0xFF);
  13. src[0] = (byte) (value & 0xFF);
  14. return src;
  15. }

将int数值转换为占四个字节的byte数组,本方法适用于(高位在前,低位在后)的顺序。 和bytesToInt2()配套使用

  1. public static byte[] intToBytes2(int value)
  2. {
  3. byte[] src = new byte[4];
  4. src[0] = (byte) ((value>>24) & 0xFF);
  5. src[1] = (byte) ((value>>16)& 0xFF);
  6. src[2] = (byte) ((value>>8)&0xFF);
  7. src[3] = (byte) (value & 0xFF);
  8. return src;
  9. }

/**
* byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用
*
* @param src
* byte数组
* @param offset
* 从数组的第offset位开始
* @return int数值
*/

  1. public static int bytesToInt(byte[] src, int offset) {
  2. int value;
  3. value = (int) ((src[offset] & 0xFF)
  4. | ((src[offset+1] & 0xFF)<<8)
  5. | ((src[offset+2] & 0xFF)<<16)
  6. | ((src[offset+3] & 0xFF)<<24));
  7. return value;
  8. }

/**
* byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用
*/

  1. public static int bytesToInt2(byte[] src, int offset) {
  2. int value;
  3. value = (int) ( ((src[offset] & 0xFF)<<24)
  4. |((src[offset+1] & 0xFF)<<16)
  5. |((src[offset+2] & 0xFF)<<8)
  6. |(src[offset+3] & 0xFF));
  7. return value;
  8. }

第二种:1、int与byte[]之间的转换(类似的byte short,long型)

/**
* 将int数值转换为占四个字节的byte数组,本方法适用于(低位在前,高位在后)的顺序。
* @param value
* 要转换的int值
* @return byte数组
*/

  1. public static byte[] intToBytes(int value)
  2. {
  3. byte[] byte_src = new byte[4];
  4. byte_src[3] = (byte) ((value & 0xFF000000)>>24);
  5. byte_src[2] = (byte) ((value & 0x00FF0000)>>16);
  6. byte_src[1] = (byte) ((value & 0x0000FF00)>>8);
  7. byte_src[0] = (byte) ((value & 0x000000FF));
  8. return byte_src;
  9. }

byte[]转int

/**
* byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
*
* @param ary
* byte数组
* @param offset
* 从数组的第offset位开始
* @return int数值
*/

  1. public static int bytesToInt(byte[] ary, int offset) {
  2. int value;
  3. value = (int) ((ary[offset]&0xFF)
  4. | ((ary[offset+1]<<8) & 0xFF00)
  5. | ((ary[offset+2]<<16)& 0xFF0000)
  6. | ((ary[offset+3]<<24) & 0xFF000000));
  7. return value;
  8. }

发表评论

表情:
评论列表 (有 0 条评论,323人围观)

还没有评论,来说两句吧...

相关阅读