java 发送16进制数据'_java 16进制数据递增

基本思路

String hex="ff"

String binString = hex -> bin

String addBinString = binString + N

String resultHex = addBinString -> hex

return resultHex

转换方法

//16->2

public static String hexString2binaryString(String hexString) {

if (hexString.length() % 2 != 0) {

hexString = "0" + hexString;

}

String bString = "", tmp;

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

tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));

bString += tmp.substring(tmp.length() - 4);

}

return bString;

}

//2->16

public static String binaryString2hexString(String bString) {

if (bString.length() % 8 != 0) {

String sbuwei = "00000000";

bString = sbuwei.substring(0, sbuwei.length() - bString.length() % 8) + bString;

}

StringBuilder tmp = new StringBuilder();

int iTmp = 0;

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

iTmp = 0;

for (int j = 0; j < 4; j++) {

iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);

}

tmp.append(Integer.toHexString(iTmp));

}

return tmp.toString();

}

public String addBinary(String a, String b) {

int carry = 0;

int sum = 0;

int opa = 0;

int opb = 0;

StringBuilder result = new StringBuilder();

while (a.length() != b.length()) {

if (a.length() > b.length()) {

b = "0" + b;

} else {

a = "0" + a;

}

}

for (int i = a.length() - 1; i >= 0; i--) {

opa = a.charAt(i) - '0';

opb = b.charAt(i) - '0';

sum = opa + opb + carry;

if (sum >= 2) {

result.append((char) (sum - 2 + '0'));

carry = 1;

} else {

result.append((char) (sum + '0'));

carry = 0;

}

}

if (carry == 1) {

result.append("1");

}

return result.reverse().toString();

}

调用代码

String hexString = "00010203040506070809aabbccddeeff";

String binaryString = hexString2binaryString(hexString);

for (int i = 0; i < 10; i++) {

String addBinaryString = addBinary(binaryString, hexString2binaryString(String.valueOf(i)));

String addHexString = binaryString2hexString(addBinaryString);

System.out.println(addHexString);

}

执行结果

00010203040506070809aabbccddeeff

00010203040506070809aabbccddef00

00010203040506070809aabbccddef01

00010203040506070809aabbccddef02

00010203040506070809aabbccddef03

00010203040506070809aabbccddef04

00010203040506070809aabbccddef05

00010203040506070809aabbccddef06

00010203040506070809aabbccddef07

00010203040506070809aabbccddef08

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值