概述
16进制字符串转2进制
2进制转16进制字符串
查找byte数组中存在的重复连续的位置第一个
public class Main1 {
public static void main(String[] args) {
System.out.println("Hello world! ");
}
/**
* 查找byte数组中存在的重复连续的位置第一个
*
* @param source {0x01,0x02,0x03}
* @param dest {0x01,0x02}
* @return 0
*/
public static int indexOf(byte[] source, byte[] dest) {
if (null == source || source.length <= 0 || null == dest || dest.length <= 0) {
return -1;
}
int sourceLen = source.length;
int destLen = dest.length;
if (sourceLen < destLen) {
return -1;
}
for (int i = 0; i <= sourceLen - destLen; i++) {
int index = i;
for (int j = 0; j < destLen; j++) {
byte bt = source[j + i];
if (bt != dest[j]) {
index = -1;
break;
}
}
if (index != -1) {
return index;
}
}
return -1;
}
/**
* 求和
*
* @param buff
* @return
*/
public static int sumByte(byte[] buff) {
int sum = 0;
if (null == buff || buff.length <= 0) {
return sum;
}
for (byte b : buff) {
sum += byte2int(b);
}
return sum & 0xFF;
}
/**
* byte转int
*
* @param b
* @return
*/
public static int byte2int(byte b) {
return b < 0 ? 256 + b : b;
}
public static String byte2hexStr(byte b) {
String s = Integer.toHexString(0xFF & b);
if (s.length() < 2) {
s = "0" + s;
}
return s.toUpperCase();
}
/**
* 2进制转16进制字符串
*
* @param b
* @return
*/
public static String byte2hexStr(byte[] b) {
if (null == b || b.length <= 0) {
return "";
}
StringBuilder sb = new StringBuilder(b.length);
for (byte value : b) {
sb.append(byte2hexStr(value));
}
return sb.toString();
}
/**
* 字符串转byte数组
*
* @param hex
* @return
*/
public static byte[] hexStr2byte(String hex) {
byte[] b = null;
if (null == hex || hex.length() <= 0) {
return b;
}
hex = hex.toUpperCase();
int len = hex.length() / 2;
char[] hexChars = hex.toCharArray();
b = new byte[len];
for (int i = 0; i < len; i++) {
int pos = i * 2;
b[i] = (byte) (char2byte(hexChars[pos]) << 4 | char2byte(hexChars[pos + 1]));
}
return b;
}
/**
* char 转byte
*
* @param c
* @return
*/
public static byte char2byte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 两个字节表示数据长度
*
* @param len 255
* @return 00FF
*/
public static byte[] setLen(int len) {
byte[] buff = new byte[2];
buff[0] = (byte) (len / 256);
buff[1] = (byte) (len % 256);
return buff;
}
/**
* 解析两位的数据长度 00FF
*
* @param l 00
* @param r FF
* @return 255
*/
public static int getLen(byte l, byte r) {
return byte2int(l) * 256 + byte2int(r);
}
}
最后
以上就是英勇板栗为你收集整理的java byte 16进制字符串相关操作的全部内容,希望文章能够帮你解决java byte 16进制字符串相关操作所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复