最近 作一个Cassandra 的项目,需要bytes[]和各种类型的转换,java 干了这么多年,应该是信手拈来,但是我错了,搞了半天才搞出来, 惭愧呀
public static final byte[] bytes(String s) {
try {
return s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError(
"Cannot happen because this *is* valid encoding.");
}
}
/** Encode a long in big-endian order */
public static final byte[] bytes(long n) {
ByteBuffer buf = ByteBuffer.allocate(8);
buf.putLong(n);
return buf.array();
}
/** Encode a long in big-endian order */
public static final byte[] bytes(int n) {
ByteBuffer buf = ByteBuffer.allocate(4);
buf.putInt(n);
return buf.array();
}
public static final String bytes2String(byte[] bs) {
try {
return new String(bs, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError(
"Cannot happen because this *is* valid encoding.");
}
}
/** Decode a long in big-endian order */
public static final long bytes2Long(byte[] bs){
assert bs.length==8;
ByteBuffer bb = ByteBuffer.wrap(bs);
return bb.getLong();
// ByteBuffer buf = ByteBuffer.allocate(8);
// buf.put(bs);
// return buf.getLong();
}
public static final int bytes2Int(byte[] bs){
assert bs.length==4;
ByteBuffer bb = ByteBuffer.wrap(bs);
return bb.getInt();
}