赫夫曼编码

2019-06-17  本文已影响0人  RalapHao
  1. 对已有Byte做压缩处理,主要利用带权最短路径,使用最短的byte代表出现最多字节
  2. 根据byte[]与权重(byte出现次数)生成赫夫曼树,向左定义为0,向右定义为1.求出每个值得编码,
  3. 压缩将byte[]用编码值代替, 并转为byte[]
  4. 解压就是压缩的逆过程
public class HuffmanDecode {

    public static void main(String[] args) {
        String content = "i like you like you miss you like miss only you";
        HuffmanDecode hd = new HuffmanDecode();
        byte[] bytes = hd.huffmanZip(content.getBytes());
        byte[] byteDatas = hd.huffmanUnZip(bytes);
        System.out.println(new String(byteDatas));
    }

    Map<Byte, String> tableMap = new HashMap<>();

    public byte[] huffmanZip(byte[] bytes) {
        List<Node> list = createList(bytes);
        Node root = createHuffmanTree(list);
        getCode(root);
        String sendCode = createSendCode(bytes);
        System.out.println(sendCode);
        byte[] zipCode = bitStrToByte(sendCode);
        return zipCode;
    }

    public byte[] huffmanUnZip(byte[] bytes) {
        List<Byte> byteList = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(byteToBitStr(bytes[i], i == bytes.length - 1 ? false : true));
        }
        Map<String, Byte> byteMap = new HashMap<>();
        tableMap.forEach((key, value) -> {
            byteMap.put(value, key);
        });
        String receiveCode = sb.toString();
        for (int i = 0; i < receiveCode.length(); ) {

            boolean flag = true;
            Byte charCode = null;
            int count = 0;
            while (flag) {
                String key = receiveCode.substring(i, i + count);
                charCode = byteMap.get(key);
                if (charCode == null) {
                    count++;
                } else {
                    flag = false;
                }
                if (i + count > receiveCode.length()) {
                    flag = false;
                }
            }
            byteList.add(charCode);
            i += count;
        }
        byte[] byteDatas = new byte[byteList.size()];
        for (int i = 0; i < byteList.size(); i++) {
            byteDatas[i] = byteList.get(i);
        }
        return byteDatas;
    }

    private String byteToBitStr(byte b, boolean flag) {
        int temp = b;
        if (flag) {
            temp |= 256;
        }
        String binaryStr = Integer.toBinaryString(temp);
        if (flag) {
            binaryStr = binaryStr.substring(binaryStr.length() - 8);
        }
        return binaryStr;
    }

    private String createSendCode(byte[] bytes) {
        StringBuilder codes = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            codes.append(tableMap.get(bytes[i]));
        }
        return codes.toString();
    }

    public byte[] bitStrToByte(String codeStr) {
        byte[] codes = codeStr.getBytes();
        int byteSize = (codes.length + 7) / 8;
        byte[] bytes = new byte[byteSize];
        for (int i = 0; i < byteSize; i++) {
            String byteData = null;
            if (i * 8 + 9 > codeStr.length()) {
                byteData = codeStr.substring(i * 8, codeStr.length());
            } else {

                byteData = codeStr.substring(i * 8, 8 * (i + 1));
            }
            bytes[i] = (byte) Integer.parseInt(byteData, 2);
        }
        return bytes;
    }

    private Node createHuffmanTree(List<Node> list) {
        if (list.size() <= 1) {
            return list.get(0);
        }
        Collections.sort(list);
        Node left = list.get(0);
        Node right = list.get(1);
        Node parent = new Node(null, left.weigth + right.weigth);
        parent.left = left;
        parent.right = right;
        list.set(0, parent);
        list.remove(1);
        return createHuffmanTree(list);
    }

    public void getCode(Node node) {
        StringBuilder bf = new StringBuilder();
        getCode(node, "", bf);
    }

    public void getCode(Node node, String code, StringBuilder b1) {
        StringBuilder b2 = new StringBuilder(b1);
        b2.append(code);

        if (node != null) {
            if (node.data == null) {
                getCode(node.left, "0", b2);
                getCode(node.right, "1", b2);
            } else {
                tableMap.put(node.data, b2.toString());
            }
        }
    }

    public void preOrder(Node node) {
        System.out.println(node);
        if (node.left != null) {
            preOrder(node.left);
        }
        if (node.right != null) {
            preOrder(node.right);
        }
    }

    public void show(List<Node> list) {
        list.forEach(System.out::println);
    }

    public void showCode() {
        System.out.println(tableMap);
    }

    public List<Node> createList(byte[] contentBytes) {
        Map<Byte, Integer> map = new HashMap<>();
        for (int i = 0; i < contentBytes.length; i++) {
            byte curByte = contentBytes[i];
            if (map.containsKey(curByte)) {
                int count = map.get(curByte);
                map.put(curByte, ++count);
            } else {
                map.put(curByte, 1);
            }
        }
        List<Node> list = new ArrayList<>();
        map.forEach((key, value) -> {
            list.add(new Node(key, value));
        });
        return list;
    }
}

class Node implements Comparable<Node> {

    public Byte data;
    public int weigth;
    public Node left;
    public Node right;

    public Node(Byte data, int weigth) {
        this.data = data;
        this.weigth = weigth;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Node{");
        sb.append("data=").append(data);
        sb.append(", weigth=").append(weigth);
        sb.append('}');
        return sb.toString();
    }

    @Override
    public int compareTo(Node o) {
        return this.weigth - o.weigth;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读