Mutual conversion between string and byte array in Java

preface

When Java communicates with programs written in other languages through TCP / IP socket, the communication contents are generally converted into byte array type. Java is also very convenient in character and array conversion. Let's learn about the principle of conversion between string and byte

principle

As we all know, in Java, byte type occupies one byte, that is, 8 bits, while hexadecimal characters occupy 4 bits, so each byte can be represented by two characters, and vice versa.

for instance

Expressed in binary: 0111 1011

Every 4 bits are represented by characters: 7 b

Yes, the principle is so simple. Next, it is implemented in Code:

Byte [] to hexadecimal string

Method 1

Idea: first convert byte [] to dimension char [] and then convert char [] to string

Method 2

Idea: first convert byte to int type, and then convert to string

Hexadecimal string to byte []

Idea: first convert the string to char [], and then to byte []

Note: Note 1 gets xxx0000 and note 2 gets 0000xxxx. Phase or convert two characters into a byte.

Another example

MD5 encryption

summary

Well, I should understand. It's not difficult. The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. If you have any questions, you can leave a message.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>