从一个byte数组中取出对应的byte的值转换为十进制、十六进制

  • Post author:
  • Post category:其他


/**

* byte[]转16进制字符串

* @param b

* @return

*/

public static String bytes_String16(byte[] b) {


StringBuilder sb = new StringBuilder();

for(int i=0;i<b.length;i++) {


sb.append(String.format(“%02x”, b[i]));

}

return sb.toString();

}

/**

* 十进制转16进制

* @param n

* @return

*/

private static String intToHex(int n) {


StringBuilder sb = new StringBuilder(8);

String a;

char []b = {‘0′,’1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’A’,’B’,’C’,’D’,’E’,’F’};

if(n==0){


return “00”;

}

while(n != 0){


if(n<0){


n= 256 +n;

}

sb = sb.append(b[n%16]);

n = n/16;

}

a = sb.reverse().toString();

if(a.length() == 1){


a= “0”+a;

}

return a;

}

/**

* 16进制字符转byte数组

* @param str

* @return

*/

public static byte[] hexStrToByteArray(String str)

{


if (str == null) {


return null;

}

if (str.length() == 0) {


return new byte[0];

}

byte[] byteArray = new byte[str.length() / 2];

for (int i = 0; i < byteArray.length; i++){


String subStr = str.substring(2 * i, 2 * i + 2);

byteArray[i] = ((byte)Integer.parseInt(subStr, 16));

}

return byteArray;

}

/**

* 获取开始下标到结束下标的16进制的值

* @param start

* @param end

* @param params

* @return

*/

public static String getStartToEndForHex(int start,int end,byte[] params){


String result = “”;

for(int i=start;i<=end;i++){


if(i==end){


result = result+intToHex(params[i]);

}else{


result = result+intToHex(params[i])+”:”;

}

}

return result;

}

/**

* 获取开始下标到结束下标的10进制的值

* @param start

* @param end

* @param params

* @return

*/

public static String getStartToEndForInt(int start,int end,byte[] params){


String result = “”;

for(int i=start;i<=end;i++){


int temp = params[i];

if(temp < 0){


temp = 256 + temp;

}

if(i==end){


result = result+temp;

}else{


result = result+temp+”:”;

}

}

return result;

}

/**

* 获取低位到高位的移位+或运算的值

* @param indexLow

* @param indexHigh

* @param params

* @return

*/

public static String getLowConactHighEndForInt(int indexLow,int indexHigh,byte[] params){


String result = “”;

int tempResult = 0;

for(int i = indexLow;i<=indexHigh;i++){


int temp = (params[i] < 0 ? 256 + params[i] : params[i]);

int tempmov = (indexHigh-i)+2;

tempmov = (i == indexHigh ? 0 : (int) Math.pow(2, tempmov));

tempResult = (temp << tempmov) | tempResult;

}

return result+tempResult;

}



版权声明:本文为qq_15139447原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。