1. 数据类型
1.1 整型
1.1.1 定长整型
定长整型最小位在最前,一共有如下几种定长整型:
int<1>
int<2>
int<3>
int<4>
int<6>
int<8>
例如:int<3>表示1为:
01 00 00
1.1.2 长度编码整型
int
根据长度不同,长度编码整型有不同的编码:
如果值<251,则存储为1字节整型
如果值≥251并<2^16,则存储为以0xfc开头+2字节整型
如果值≥2^16并<2^24,则存储为以0xfd开头+3字节整型
如果值≥2^24并<2^64,则存储为以0xfe开头+8字节整型
举例:
fa -- 250
fc fb 00 -- 251
1.1.3 实现
Int.java:
package io.timberwolf.net.protocols.mysql.data;
import com.google.common.base.Preconditions;
import java.nio.ByteBuffer;
/** * MySQL protocol DataType - Integer Types * * @author Hash Zhang * @version 0.0.0 * @see @http://dev.mysql.com/doc/internals/en/integer.html */
public class Int {
//定长整型数据编码解码
public static int writeLength1(ByteBuffer buffer, int num) {
Preconditions.checkArgument(num < 0x100);
buffer.put((byte) num);
return 1;
}
public static int readLength1(ByteBuffer buffer) {
Preconditions.checkNotNull(buffer);
return (int) buffer.get();
}
public static int writeLength2(ByteBuffer buffer, int num) {
Preconditions.checkArgument(num < 0x10000);
buffer.