美文网首页
赫夫曼编码

赫夫曼编码

作者: RalapHao | 来源:发表于2019-06-17 16:54 被阅读0次
  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;
    }
}

相关文章

  • 树结构入门教程-赫夫曼解码

    上节我们学习赫夫曼编码的过程,这节我们来学习赫夫曼编码的逆操作---------->解码操作,由于我们对编码的过程...

  • 赫夫曼编码

    哈夫曼编码是 1952 年由 David A. Huffman 提出的一种无损数据压缩的编码算法。哈夫曼编码先统计...

  • 赫夫曼编码

    赫夫曼编码 赫夫曼编码在数据压缩领域有着广泛的应用,压缩率在20%-90%,是一种重要的算法 算法思想(以字符串压...

  • 赫夫曼编码

    对已有Byte做压缩处理,主要利用带权最短路径,使用最短的byte代表出现最多字节 根据byte[]与权重(byt...

  • 十八. java数据结构 - 赫夫曼编码数据压缩与解压

    赫夫曼编码压缩文件注意事项 如果文件本身就是经过压缩处理的,那么使用赫夫曼编码再压缩效率不会有明显变化, 比如视频...

  • 数据结构与算法之二叉树(二)赫夫曼编码原理及实现

    引言 上篇博客学习了二叉树的基本操作原理,今天我们在此基础上学习二叉树的典型应用:赫夫曼编码树,赫夫曼编码(Huf...

  • 赫夫曼编码&解码

    之前说到了如何构建赫夫曼树,那么赫夫曼树有什么用呢?赫夫曼树经典的应用之一就是赫夫曼编码。 1. 赫夫曼编码是什么...

  • 十七. java数据结构 - 赫夫曼编码概述

    1.基本介绍 赫夫曼编码也翻译为 哈夫曼编码(Huffman Coding),又称霍夫曼编码,是一种编码方式, 属...

  • 霍夫曼编码

    概念 霍夫曼编码(Huffman Coding),又译为哈夫曼编码、赫夫曼编码,是一种用于无损数据压缩的熵编码(权...

  • 【离散数学】树(一)哈夫曼编码基本原理

    正文之前 霍夫曼编码(Huffman Coding),又译为哈夫曼编码、赫夫曼编码,是一种用于无损数据压缩的熵编码...

网友评论

      本文标题:赫夫曼编码

      本文链接:https://www.haomeiwen.com/subject/dyczfctx.html