package com.sdyc.ndmp.protobuf.serializer;
import java.nio.charset.Charset;
/**
*
*
* Created by IntelliJ IDEA.
* User: ZhenQin
* Date: 13-10-8
* Time: 上午9:57
* To change this template use File | Settings | File Templates.
*
*
*
* @author ZhenQin
*/
public class StringSerializer implements Serializer {
private static final long serialVersionUID = 1L;
/**
* 默认支持的编码类型
*/
private Charset charset = Charset.forName("UTF-8");
/**
* 默认是UTF-8的数据编码类型
*/
public StringSerializer() {
}
/**
* 自己指定数据编码类型
* @param charset
*/
public StringSerializer(Charset charset) {
this.charset = charset;
}
/**
* 自己指定数据编码类型
* @param charset
*/
public StringSerializer(String charset) {
this.charset = Charset.forName(charset);
}
/**
* Serialize the given object to binary data.
*
* @param s object to serialize
* @return the equivalent binary data
*/
@Override
public byte[] serialize(String s) {
return s.getBytes(charset);
}
public String deserialize(byte[] bytes, int offset, int length) {
return new String(bytes, offset, length, charset);
}
/**
* Deserialize an object from the given binary data.
*
* @param bytes object binary representation
* @return the equivalent object instance
*/
@Override
public String deserialize(byte[] bytes) {
return new String(bytes, charset);
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
/**
* 把非字符串化的字符串转换成 String
* @param bytes
* @return
*/
public static String toString(byte[] bytes) {
StringBuffer strBuf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
}
return strBuf.toString();
}
/**
* 把非字符串化的字符串转换成 byte
* @param str
* @return
*/
public static byte[] toBytes(String str) {
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length(); i += 2) {
char c = str.charAt(i);
bytes[i / 2] = (byte) ((c - 'a') << 4);
c = str.charAt(i + 1);
bytes[i / 2] += (c - 'a');
}
return bytes;
}
}