⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 byteconvert.java

📁 java版源代码,里面包含很多源代码,大家可以看看.
💻 JAVA
字号:
package com.trulytech.mantis.util;

/**
 *
 * <p>Title: Mantis</p>
 *
 * <p>Description: Byte类型转换类</p>
 *
 * <p>Copyright: Copyright (c) 2002</p>
 *
 * <p>Company: </p>
 *
 * @author Wang Xian
 * @version 1.0
 */
public class ByteConvert {

  /**
   * 将一个int转换成4个byte
   * @param n int
   * @return byte[]
   */
  public static byte[] int2byte(int n) {
    byte b[] = new byte[4];
    b[0] = (byte) (n >> 24);
    b[1] = (byte) (n >> 16);
    b[2] = (byte) (n >> 8);
    b[3] = (byte) n;
    return b;
  }

  /**
   * 将四个byte转换成一个int
   * @param b byte[]
   * @param offset int
   * @return int
   */
  public static int byte2int(byte b[], int offset) {
    return b[offset + 3] & 0xff | (b[offset + 2] & 0xff) << 8 |
        (b[offset + 1] & 0xff) << 16 | (b[offset] & 0xff) << 24;
  }

  /**
   * 将一个short转换为2个byte
   * @param b byte[]
   * @param offset int
   * @return short
   */
  public static short byte2short(byte[] b, int offset) {
    return (short) ( (b[offset + 1] & 0xFF) +
                    ( ( ( (short) b[offset]) << 8) & 0xFF00));

  }

  /**
   * 将一个short转换成2个byte
   * @param n int
   * @return byte[]
   */
  public static byte[] short2byte(short n) {
    byte b[] = new byte[2];
    b[0] = (byte) (n >> 8);
    b[1] = (byte) n;
    return b;
  }

  /**
   * 将一个long转换成8个byte
   * @param n long
   * @return byte[]
   */
  public static byte[] long2byte(long n) {
    byte b[] = new byte[8];
    b[0] = (byte) (int) (n >> 56);
    b[1] = (byte) (int) (n >> 48);
    b[2] = (byte) (int) (n >> 40);
    b[3] = (byte) (int) (n >> 32);
    b[4] = (byte) (int) (n >> 24);
    b[5] = (byte) (int) (n >> 16);
    b[6] = (byte) (int) (n >> 8);
    b[7] = (byte) (int) n;
    return b;
  }

  /**
   * 将四个byte转换成一个long
   * @param b byte[]
   * @param offset int
   * @return long
   */
  public static long byte2long(byte b[], int offset) {
    return (long) b[offset + 7] & (long) 255 |
        ( (long) b[offset + 6] & (long) 255) << 8 |
        ( (long) b[offset + 5] & (long) 255) << 16 |
        ( (long) b[offset + 4] & (long) 255) << 24 |
        ( (long) b[offset + 3] & (long) 255) << 32 |
        ( (long) b[offset + 2] & (long) 255) << 40 |
        ( (long) b[offset + 1] & (long) 255) << 48 | (long) b[offset] << 56;
  }

  /**
   * 用16进制显示byte[]
   * @param bs byte[]
   * @param SplitStr String 每个byte的分割符
   * @return String
   */
  public static String HexBytes(byte[] bs, String SplitStr) {
    StringBuffer ret = new StringBuffer(bs.length);
    for (int i = 0; i < bs.length; i++) {
      String hex = Integer.toHexString(0x0100 + (bs[i] & 0x00FF)).substring(1);
      ret.append( (hex.length() < 2 ? "0" : "") + hex + SplitStr);
    }
    return ret.toString();
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -