PackBits算法

来源:互联网 发布:淘宝基金欠款 编辑:程序博客网 时间:2024/06/05 23:39
          位压缩算法是一种应用于数据长度编码的快速,简单无损的数据压缩方案。
         苹果公司在Mactionsh计算机上首先推出的这种算法。这是一种可以用在TIFF文件上的压缩算法。TAG文件也使用这种RLE压缩方案,但是其将数据视为像素而不是字节。
        一个压缩位数据流是以一个字节的头(header),后接数据(data)的形式组织数据:数据可以被标记,不标记或者进行压缩。在下面的表中,n是被做了标记的Data的数据个数。
HeaderData 0--127(1+n)个文本数据-1----- -127在解压缩的时候,一个字节的数据被复制(1-n)次128无操作。(跳过此字节直接处理下个header后接的数据
       注意:压缩解压缩的时候将0作为负数或者整数无影响。连个相近的字节被视为是文本数据。另外也需要注意的是,根据位压缩算法并不能决定数据流是否终止。换句话说:在进行压缩或者解压缩的时候必须事先知道数据的长度。
        苹果公司提供了如下简短压缩后的数据:FE AA 02 80 00 2A FD AA 03 80 00 2A 22 F7 AA
依据压缩算法,相应的解压缩算法:(VB)代码如下:
  1. Sub UnpackBitsDemo()
  2. Dim File As Variant
  3. Dim MyOutput As String
  4. Dim Count As Long
  5. Dim i As Long, j As Long
  6. File = "FE AA 02 80 00 2A FD AA 03 80 00 2A 22 F7 AA"
  7. File = Split(File, " ")
  8. For i = LBound(File) To UBound(File)
  9. Count = Application.WorksheetFunction.Hex2Dec(File(i))
  10. Select Case Count
  11. Case Is >= 128
  12. Count = 256 - Count 'Two's Complement
  13. For j = 0 To Count 'zero-based
  14. MyOutput = MyOutput & File(i + 1) & " "
  15. Next j
  16. i = i + 1 'Adjust the pointer
  17. Case Else
  18. For j = 0 To Count 'zero-based
  19. MyOutput = MyOutput & File(i + j + 1) & " "
  20. Next j
  21. i = i + j 'Adjust the pointer
  22. End Select
  23. Next i
  24. Debug.Print MyOutput
  25. 'AA AA AA 80 00 2A AA AA AA AA 80 00 2A 22 AA AA AA AA AA AA AA AA AA AA
  26. End Sub
JS的实例如下:
  1. /**
  2. * Helper functions to create readable input and output
  3. *
  4. * Also, see this fiddle for interactive PackBits decoder:
  5. * https://jsfiddle.net/volter9/tj04ejdt/
  6. */
  7. function str2hex (str) {
  8. return str.split('').map(function (char) {
  9. var value = char.charCodeAt(0);
  10. return ((value < 16 ? '0' : '') + value.toString(16)).toUpperCase();
  11. }).join(' ');
  12. }
  13. function hex2str (hex) {
  14. return hex.split(' ').map(function (string) {
  15. return String.fromCharCode(parseInt(string, 16));
  16. }).join('');
  17. }
  18. /**
  19. * PackBits unpack function
  20. *
  21. * @param {String} data
  22. * @return {String}
  23. */
  24. function unpackBits (data) {
  25. var output = '',
  26. i = 0;
  27. while (i < data.length) {
  28. var hex = data.charCodeAt(i);
  29. if (hex >= 128) {
  30. hex = 256 - hex;
  31. for (var j = 0; j <= hex; j ++) {
  32. output += data.charAt(i + 1);
  33. }
  34. i ++;
  35. }
  36. else {
  37. for (var j = 0; j <= hex; j ++) {
  38. output += data.charAt(i + j + 1);
  39. }
  40. i += j;
  41. }
  42. i ++;
  43. }
  44. return output;
  45. }
  46. var original = 'FE AA 02 80 00 2A FD AA 03 80 00 2A 22 F7 AA',
  47. data = unpackBits(hex2str(original));
  48. // Output is: AA AA AA 80 00 2A AA AA AA AA 80 00 2A 22 AA AA AA AA AA AA AA AA AA AA
  49. console.log(str2hex(data));




参考链接:https://en.wikipedia.org/wiki/PackBits

原创粉丝点击