当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java位操作
发布时间:2010/6/25 11:38:56 来源:城市学习网 编辑:ziteng
  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;
  } [NextPage]   /**
  * 将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;
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved