1_1
package outerquestion1.innerquestion1;
public class Answer {
/**
* 十进制转二进制,十进制转Varint
*/
public static void main(String[] args) {
// 1010011010
// 1001101000000101
// 1101111000
// 1111100000000110
//十进制转二进制
System.out.println(Integer.toBinaryString(666));
//十进制转varint
System.out.println(getBinarystrFromByteArr(encode(666)));
//十进制转二进制
System.out.println(Integer.toBinaryString(888));
//十进制转vacint
System.out.println(getBinarystrFromByteArr(encode(888)));
}
public static byte[] encode(int val) {
byte[] data = new byte[computeLength(val)];
for (int i = 0; i < data.length - 1; i++) {
data[i] = (byte) ((val & 0x7F) | 0x80);
val = val >>> 7;
}
data[data.length - 1] = (byte) (val);
return data;
}
/**
* 把int转为varint编码需要的字节数,每次无符号右移7位,直到为0。返回值为1-5
*
* @return
*/
public static int computeLength(int val) {
if (val == 0) {
return 1;
}
int length = 0;
while (val != 0) {
val = val >>> 7;
length++;
}
return length;
}
/**
* 把byte数组转化成2进制字符串
*
* @param bArr
* @return
*/
public static String getBinarystrFromByteArr(byte[] bArr) {
StringBuilder result = new StringBuilder();
for (byte b : bArr) {
result.append(getBinarystrFromByte(b));
}
return result.toString();
}
public static String getBinarystrFromByte(byte b) {
StringBuilder result = new StringBuilder();
byte a = b;
for (int i = 0; i < 8; i++) {
byte c = a;
a = (byte) (a >> 1);//每移一位如同将10进制数除以2并去掉余数。
a =