123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- package com.sdyc.ndmp.protobuf.serializer;
- import java.nio.charset.Charset;
- /**
- * <pre>
- *
- * Created by IntelliJ IDEA.
- * User: ZhenQin
- * Date: 13-10-8
- * Time: 上午9:57
- * To change this template use File | Settings | File Templates.
- *
- * </pre>
- *
- * @author ZhenQin
- */
- public class StringSerializer implements Serializer<String> {
- 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;
- }
- }
|