[java] Conversion of hexadecimal, byte, and String in java

In the blogger’s previous article, binary was briefly introduced. In addition to binary, hexadecimal is also commonly used. For example, hexadecimal often appears in the tcp (modbus) protocol that bloggers come into contact with.

How to send byte array command

We assume that in the docking, we know that the fixed instruction is a hexadecimal array. The code example is as follows:

// 16进制为例
byte rq = new byte[]{
    
    0x00,0x00,0x00,0x00,0x01,0x03}

// 在netty中为例:
channelHandlerContext.writeAndFlush(rq );
// 需要先配置编码器            
// socketChannel.pipeline().addLast("ByteArrayDecoder", new ByteArrayDecoder());


How to send dynamic byte array commands

In the above example, we know the instruction, and the instruction is fixed. In other words, the content in the byte array is hard-coded by adding the 0x prefix, so suppose our instruction is not fixed, but variable Woolen cloth?

Pseudocode to restore the scene:

int id = ?;
byte rq ;
if (id == 3){
    
    
    rq= new byte[]{
    
    0x00,0x00,0x00,0x00,0x01,0x03}
 } else if (id == 6){
    
    
     rq= new byte[]{
    
    0x00,0x00,0x00,0x00,0x01,0x06}
} else if(id == 9){
    
    
    rq= new byte[]{
    
    0x00,0x00,0x00,0x00,0x01,0x09}
}else{
    
    
	// other
}


If the id is limited, we can also define it as above, what if the id is unknown?
Students with poor foundation may have doubts and don't know how to define it.

We just need to directly convert int to byte

    rq= new byte[]{
    
    0x00,0x00,0x00,0x00,0x01,(byte) id};

byte and int conversion problem

As mentioned above, it is good to force int to byte, but there is a range problem in the conversion between byte and int:

		int t = 255;
		// (byte范围是-128-127)
        byte tt = (byte) t; // -1
        // 而byte是可以直接转int的
        int ttt = tt; // -1
       

It can be seen that when the byte is a negative number, there will be a problem if it is directly converted back to int, so how do we get the original number of int? We need to do an AND operation between tt and 0xFF to get an unsigned number
(provided that int must be a positive number).

int res = tt & 0xFF; //255
	

Having said so much, some students may wonder why there is data in the byte range?
For example, the tcp data format given by others is: 00 00 00 00 00 04 01 02 03 FF, (hexadecimal), and the last FF byte exceeds the range.

A little knowledge of popular science: be bold, this result is trueinsert image description here

byte and byte string conversion problem

Still taking the hexadecimal system as an example, we need to introduce the hutool package,

     	   <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>5.0.7</version>
            </dependency>
	// bytes to hexStr
    byte[] bytes  = new byte[]{
    
    0x00,0x00,0x00,0x00,0x01};
    // ”0000000001“
    String hexStr =   HexUtil.encodeHexStr(bytes);
	// hexStr to bytes
	byte[] b = HexUtil.decodeHex(hexStr);

Decimal to hexadecimal string

	String str = Integer.toHexString(11); // b

If you need to occupy two lengths, that is: 0b, then manually judge the length of str and splice a 0.

str += "0"

There is still a common-sense question. Students with good foundations should not read it, as it will make them confused.

Students with poor foundation can take a look:
We can only manually declare 0x to represent hexadecimal, but it is not a type,
and cannot be directly represented by long and int types like decimal

	 		byte a = 0x01; // 16进制中01 的byte值
	        int b = 0x01;  //  16进制中01 的int值

So in our code, we generally use byte or String hexStr to represent hexadecimal,
or the example (byte) 0xFF and byte -1 are equal

Guess you like

Origin blog.csdn.net/qq_36268103/article/details/129994338