Java中byte[]、String、Hex字符串等转换的方法

2025-05-29 0 32

代码如下所示:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53
/*输入一个byte和byte[]合并为byte[]*/

public byte[] bytemerger(byte byte_1, byte[] byte_2) {

byte[] byte_3 = new byte[1 + byte_2.length];

byte_3[0] = byte_1;

system.arraycopy(byte_2, 0, byte_3, 1, byte_2.length);

return byte_3;

}

/*输入一个byte[]和byte[]合并为byte[]*/

public byte[] bytemerger(byte[] byte_1, byte[] byte_2) {

byte[] byte_3 = new byte[1 + byte_2.length];

byte_3[0] = byte_1;

system.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);

return byte_3;

}

/*输入一个string(16进制的字符hex eg:ff)输出为16进制的byte[],注意输入为小写的hex字符串*/

public byte[] hexstringtobyte(string hex) {

int len = (hex.length() / 2);

byte[] result = new byte[len];

char[] achar = hex.tochararray();

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

int pos = i * 2;

result[i] = (byte) (chartobyte(achar[pos]) << 4 | chartobyte(achar[pos + 1]));

}

//system.out.println(arrays.tostring(result));

return result;

}

private byte chartobyte(char c) {

//return (byte) "0123456789abcdef".indexof(c);

return (byte) "0123456789abcdef".indexof(c);

}

/*输入10进制数字字符串,输出hex字符串(2位,eg: f 则输出 0f)*/

string value= "100";

int parseint = integer.parseint(value, 10);

string hexstring = integer.tohexstring(parseint);

if (hexstring.length() < 2) {

hexstring = '0' + hexstring;

}

header = header + hexstring;

}

/*输入16进制byte[]输出16进制字符串*/

public static string bytearraytohexstr(byte[] bytearray) {

if (bytearray == null) {

return null;

}

char[] hexarray = "0123456789abcdef".tochararray();

char[] hexchars = new char[bytearray.length * 2];

for (int j = 0; j < bytearray.length; j++) {

int v = bytearray[j] & 0xff;

hexchars[j * 2] = hexarray[v >>> 4];

hexchars[j * 2 + 1] = hexarray[v & 0x0f];

}

return new string(hexchars);

}

ps:下面看下js对url中特殊字符的转换

?

1

2

3

4

5

6

7

8

9

10

11

12

13
let str = "http%3a%2f%2fxxxxxxxx%2findex.php%2fxxxxxxx%2fmember%2fregister%3frecommend_id%3d11442%26id%3d87";

function replacestr(str){

str = str.replace(/%3a/g, ":");

str = str.replace(/%2f/g, "/");

str = str.replace(/%3f/g, "?");

str = str.replace(/%3d/g, "=");

str = str.replace(/%26/g, "&");

str = str.replace(/%2b/g, "+");

str = str.replace(/%20/g, " ");

str = str.replace(/%23/g, "#");

return str;

}

console.log(replacestr(str));

总结

以上所述是小编给大家介绍的java中byte[]、string、hex字符串等转换的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java中byte[]、String、Hex字符串等转换的方法 https://www.kuaiidc.com/111639.html

相关文章

发表评论
暂无评论