zoukankan      html  css  js  c++  java
  • java位操作

    public class ByteConvert {


    public static byte[] stringToByte(String inputString) {
    int strLen = inputString.length();
    char[] charResult = new char[strLen];
    byte[] byteResult = new byte[strLen];

    for (int i = 0; i < strLen; i++) {
    charResult[i] = inputString.charAt(i);
    byteResult[i] = (byte) charResult[i];
    }
    return byteResult;
    }
    /**
    * 将int型转为byte[],高位byte存储高位
    * @param int inputNum
    * @return byte[]
    */
    public static byte[] intToByte(int inputNum) {

    int count = 0;
    if (inputNum < (Math.pow(2, 8)))
    count = 1;
    else if (inputNum < (Math.pow(2, 16)))
    count = 2;
    else if (inputNum < (Math.pow(2, 24)))
    count = 3;
    else if (inputNum < (Math.pow(2, 32)))
    count = 4;
    byte[] byteResult = new byte[count];
    for (int i = 0; i < count; i++) {
    byteResult[i] = (byte) ((inputNum >> (8 * i)) & 0xff);
    }
    return byteResult;

    }
    /**
    * 将byte[]转为int,高位byte存储的是高位,从高位开始解析
    * @param inputByte
    * @return int
    */
    public static int byteToInt(byte[] inputByte) {
    int count = inputByte.length;

    int result = 0;
    for (int i = count - 1; i >= 0; i--) {
    if (inputByte[i] < 0) {
    int temp = 0;
    temp = 256 + inputByte[i];
    result = (result << 8) + temp;
    } else {
    result = (result << 8) + inputByte[i];
    }
    }
    return result;
    }
    /**
    * 将byte[]转为string
    * @param inputByte
    * @return String
    */
    public static String byteToString(byte[] inputByte){
    int len=inputByte.length;
    String result="";
    for(int i=0;i<len;i++){
    result=result+(char)inputByte[i];
    }
    return result;
    }
    }
  • 相关阅读:
    第04组 beta冲刺(1/4)
    2019 SDN上机第5次作业
    SDN课程阅读作业(2)
    第04组 Alpha事后诸葛亮
    C Primer 复习题
    C Primer 编程练习
    C语言I博客作业04
    C语言I博客作业03
    C语言I博客作业02
    Appium + java截图方法
  • 原文地址:https://www.cnblogs.com/danghuijian/p/4400230.html
Copyright © 2011-2022 走看看