Created
September 12, 2018 01:32
-
-
Save huangered/76addb2da11a3864c7ca1d9193ba01d7 to your computer and use it in GitHub Desktop.
Varint64 in java code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.yih.storage; | |
import com.google.common.primitives.UnsignedBytes; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Varint64 { | |
public List<Byte> to(Long num) { | |
List<Byte> bytes = new ArrayList<>(); | |
while (num >= 128) { | |
Long j = ((num & 127) | 128); | |
bytes.add(j.byteValue()); | |
num >>= 7; | |
} | |
bytes.add(num.byteValue()); | |
return bytes; | |
} | |
public Long from(List<Byte> input) { | |
long ret = 0; | |
for (int i = 0; i < input.size(); i++) { | |
ret |= (input.get(i) & 127) << (7 * i); | |
if ((input.get(i) & 128) == 0) { | |
break; | |
} | |
} | |
return ret; | |
} | |
public static void main(String[] argc) { | |
Varint64 varint64 = new Varint64(); | |
List<Byte> dd = varint64.to((long) 0xCAFE); | |
for (Byte d : dd) { | |
System.out.println(UnsignedBytes.toString(d)); | |
} | |
Long ret = varint64.from(dd); | |
System.out.println(ret); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment