-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
LZW #5
Open
kamendov-maxim
wants to merge
9
commits into
master
Choose a base branch
from
LZW
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
LZW #5
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
5d66c13
Функция для преобразования
kamendov-maxim dec5f98
Обратное преобразование
kamendov-maxim 25c4716
Отредактировал gitignore
kamendov-maxim 8708ddf
Создал ветку
kamendov-maxim 6382e02
Разбил на два файла
kamendov-maxim 191d28b
Бор
kamendov-maxim 3b460c5
Merge branch 'BWT' into LZW
kamendov-maxim a215454
Merge remote-tracking branch 'origin/BWT' into LZW
kamendov-maxim 3a12e8c
LZW
kamendov-maxim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
using LZW.Dependencies; | ||
|
||
namespace Compressor; | ||
|
||
internal static class Compressor | ||
{ | ||
public static byte[] Compress(byte[] bytes, int BWTPosition = -1) | ||
{ | ||
var trie = new Trie(); | ||
var buffer = new ByteBuffer(); | ||
buffer.SetBWTPosition(BWTPosition); | ||
for (int i = 0; i < bytes.Length; ++i) | ||
{ | ||
if (trie.Size == buffer.MaxSize) | ||
{ | ||
buffer.MaxSize *= 2; | ||
++buffer.currentBitCount; | ||
} | ||
int number = trie.Add(ref i, bytes); | ||
buffer.AddNumber(number); | ||
} | ||
return buffer.ToByteArray(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
using System.ComponentModel; | ||
using System.Runtime.ExceptionServices; | ||
using System.Runtime.Serialization.Formatters; | ||
using LZW.Dependencies; | ||
|
||
namespace Compressor; | ||
|
||
internal class Decompressor | ||
{ | ||
public static byte[] Decompress(byte[] bytes) | ||
{ | ||
if (bytes.Length == 0) | ||
{ | ||
throw new InvalidDataException("empty byte sequence"); | ||
} | ||
|
||
Dictionary<int, List<byte>> dictionary = new(); | ||
|
||
for (int i = 0; i < 256; ++i) | ||
{ | ||
dictionary[i] = new List<byte> { (byte)(i) }; | ||
} | ||
|
||
int bwtPosition = BitConverter.ToInt32(new byte[] { bytes[0], bytes[1], bytes[2], bytes[3] }); | ||
var list = new List<byte>(bytes); | ||
list.RemoveRange(0, 4); | ||
bytes = list.ToArray(); | ||
|
||
if (bwtPosition != -1) | ||
{ | ||
bytes = BWT.Revert(bytes, bwtPosition); | ||
} | ||
|
||
int counter = 256; | ||
NumberBuffer numberBuffer = new(); | ||
|
||
for (int i = 0; i < bytes.Length; ++i) | ||
{ | ||
if (counter == numberBuffer.MaxNumber) | ||
{ | ||
numberBuffer.MaxNumber *= 2; | ||
++numberBuffer.currentBitCount; | ||
} | ||
|
||
if (numberBuffer.AddByte(bytes[i])) | ||
{ | ||
++counter; | ||
} | ||
} | ||
|
||
int[] intArray = numberBuffer.ToIntArray(); | ||
counter = 256; | ||
|
||
List<byte> decodedBytes = new(); | ||
for (int i = 0; i < intArray.Length - 1; ++i) | ||
{ | ||
decodedBytes.AddRange(dictionary[intArray[i]]); | ||
|
||
List<byte> newCodeSequence = new(); | ||
newCodeSequence.AddRange(dictionary[intArray[i]]); | ||
|
||
if (!dictionary.ContainsKey(intArray[i + 1])) | ||
{ | ||
newCodeSequence.Add(newCodeSequence[0]); | ||
dictionary[counter] = newCodeSequence; | ||
} | ||
else | ||
{ | ||
newCodeSequence.Add(dictionary[intArray[i + 1]][0]); | ||
dictionary[counter] = newCodeSequence; | ||
} | ||
|
||
++counter; | ||
} | ||
return decodedBytes.ToArray(); | ||
} | ||
|
||
// private static (int[], int) getNumbersAndBwtPosition(byte[] bytes) | ||
// { | ||
// int bwtPosition = BitConverter.ToInt32(new byte[] { bytes[0], bytes[1], bytes[2], bytes[3] }); | ||
// var buffer = new NumberBuffer(); | ||
// for (int i = 5; i < bytes.Length; ++i) | ||
// { | ||
// var oneByte = bytes[i]; | ||
// buffer.AddByte(oneByte, true); | ||
// } | ||
// return (buffer.Numbers.ToArray(), bwtPosition); | ||
// } | ||
} | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,121 @@ | ||
using System.Collections; | ||
using System.Runtime.CompilerServices; | ||
using System.Threading.Tasks.Dataflow; | ||
|
||
namespace LZW.Dependencies; | ||
|
||
/// <summary> | ||
/// Класс, содержащий в себе методы для преобразования и обратного | ||
/// преобразования Барроуза-Уилера для байтовых массивов | ||
/// </summary> | ||
public class BWT | ||
{ | ||
/// <summary> | ||
/// Строит преобразование Барроуза-Уилера | ||
/// </summary> | ||
/// <param name="bytes">Байтовый массив, для которого нужно построить | ||
/// преобразование</param> | ||
/// <returns>Байтовый массив - исходный массив после преобразования\n | ||
/// и число - позиция исходной строке в таблице циклических сдвигов</returns> | ||
public static (byte[], int) Transform(byte[] bytes) | ||
{ | ||
var indexArray = new int[bytes.Length]; | ||
int BWTPosition = 0; | ||
|
||
for (int i = 0; i < bytes.Length; ++i) | ||
{ | ||
indexArray[i] = i; | ||
} | ||
|
||
Array.Sort(indexArray, (a, b) => Compare(a, b, bytes)); | ||
|
||
var transformedBytes = new byte[bytes.Length]; | ||
for (int i = 0; i < bytes.Length; ++i) | ||
{ | ||
if (indexArray[i] == 0) | ||
{ | ||
BWTPosition = i; | ||
transformedBytes[i] = bytes[bytes.Length - 1]; | ||
continue; | ||
} | ||
transformedBytes[i] = bytes[indexArray[i] - 1]; | ||
} | ||
|
||
return (transformedBytes, BWTPosition); | ||
} | ||
|
||
|
||
/// <summary> | ||
/// Обратное преобразование | ||
/// </summary> | ||
/// <param name="bytes">Байтовая последовательность, по | ||
/// которой нужно восстановить исходную</param> | ||
/// <param name="BWTPosition">Позициая исходной строки в | ||
/// таблице циклических сдвигов</param> | ||
/// <returns>Исзходная байтовая последовательность</returns> | ||
public static byte[] Revert(byte[] bytes, int BWTPosition) | ||
{ | ||
var sortedBytes = new byte[bytes.Length]; | ||
Array.Copy(bytes, sortedBytes, bytes.Length); | ||
Array.Sort(sortedBytes); | ||
|
||
var result = new byte[bytes.Length]; | ||
|
||
for (int i = 0; i < bytes.Length; ++i) | ||
{ | ||
byte currentByte = sortedBytes[BWTPosition]; | ||
result[i] = currentByte; | ||
|
||
int countF = 0; | ||
for (int k = 0; k < BWTPosition + 1; ++k) | ||
{ | ||
if (sortedBytes[k] == currentByte) | ||
{ | ||
++countF; | ||
} | ||
} | ||
|
||
int countL = 0; | ||
int j = 0; | ||
for (; countL != countF; ++j) | ||
{ | ||
if (bytes[j] == currentByte) | ||
{ | ||
++countL; | ||
} | ||
} | ||
BWTPosition = j - 1; | ||
} | ||
|
||
return result; | ||
} | ||
|
||
private static int Compare(int a, int b, byte[] bytes) | ||
{ | ||
int min = bytes.Length - (a > b ? a : b); | ||
for (int i = 0; i < min; ++i) | ||
{ | ||
if (bytes[a + i] < bytes[b + i]) | ||
{ | ||
return -1; | ||
} | ||
else if (bytes[a + i] > bytes[b + i]) | ||
{ | ||
return 1; | ||
} | ||
} | ||
if (a > b) | ||
{ | ||
return -1; | ||
} | ||
else if (a < b) | ||
{ | ||
return 1; | ||
} | ||
else | ||
{ | ||
return 0; | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
namespace LZW.Dependencies; | ||
|
||
/// <summary> | ||
/// Структура данных, представляющая собой последовательность чисел в двоичной форме, из которой можно получить байтовый массив | ||
/// </summary> | ||
class ByteBuffer | ||
{ | ||
public int MaxSize = 256; | ||
public int currentBitCount = 8; | ||
private const int BITS_IN_BYTE = 8; | ||
int currentByteSize = 0; | ||
byte currentByte = 0; | ||
List<byte> buffer = new(); | ||
|
||
/// <summary> | ||
/// Добавляет 4 байта в начале - позиция исходной строки в таблице циклических сдвигов преобразования Барроуза-Уилера | ||
/// </summary> | ||
/// <param name="position">Позиция исходной строки в таблице</param> | ||
public void SetBWTPosition(int position) | ||
{ | ||
var positionBytes = BitConverter.GetBytes(position); | ||
buffer.AddRange(positionBytes); | ||
} | ||
|
||
/// <summary> | ||
/// Метод, добавляющий число в буффер | ||
/// </summary> | ||
/// <param name="number">Число, которое нужно добавить</param> | ||
public void AddNumber(int number) | ||
{ | ||
var bits = IntToByte(number); | ||
foreach (var bit in bits) | ||
{ | ||
currentByte = (byte)((currentByte << 1) + bit); | ||
++currentByteSize; | ||
if (currentByteSize == BITS_IN_BYTE) | ||
{ | ||
currentByteSize = 0; | ||
buffer.Add(currentByte); | ||
currentByte = 0; | ||
} | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Метод, позволяющий получить байтовый массив из текущего буффера | ||
/// </summary> | ||
/// <returns>байтовый массив</returns> | ||
public byte[] ToByteArray() | ||
{ | ||
currentByte <<= BITS_IN_BYTE - currentByteSize; | ||
currentByteSize = 0; | ||
currentByte = 0; | ||
buffer.Add(currentByte); | ||
return buffer.ToArray(); | ||
} | ||
|
||
private byte[] IntToByte(int number) | ||
{ | ||
var bits = new byte[currentBitCount]; | ||
for (int i = currentBitCount - 1; i >= 0; --i) | ||
{ | ||
bits[i] = (byte)(number % 2); | ||
number /= 2; | ||
} | ||
|
||
return bits; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
using System.Transactions; | ||
|
||
namespace LZW.Dependencies; | ||
|
||
/// <summary> | ||
/// Структура данных, хранящая последовательность чисел, из которой можно получить массив | ||
/// </summary> | ||
class NumberBuffer | ||
{ | ||
public int currentBitCount = 8; | ||
private int currentNumber = 0; | ||
public int currentNumberLength = 0; | ||
private const int BITS_IN_BYTE = 8; | ||
public int MaxNumber = 256; | ||
public List<int> Numbers; | ||
|
||
public NumberBuffer() | ||
{ | ||
Numbers = new List<int>(); | ||
} | ||
|
||
/// <summary> | ||
/// Метод, позволяющий добавить число, зашифрованное байтом (число добавляется, когда наберется нужно число байт для шифрования числа) | ||
/// </summary> | ||
/// <param name="oneByte">Байт, который нужно добавить</param> | ||
/// <returns>True, если текущий байт был последним байтом числа и оно добавилось</returns> | ||
public bool AddByte(byte oneByte) | ||
{ | ||
bool newNumber = false; | ||
var bits = ByteToByteArray(oneByte); | ||
foreach (var bit in bits) | ||
{ | ||
currentNumber = (currentNumber * 2) + bit; | ||
if (++currentNumberLength == currentBitCount) | ||
{ | ||
AddNumberToBuffer(); | ||
newNumber = true; | ||
} | ||
} | ||
|
||
return newNumber; | ||
} | ||
|
||
/// <summary> | ||
/// Позволяет получить массив уже добавленных чисел | ||
/// </summary> | ||
/// <returns>Массив чисел</returns> | ||
public int[] ToIntArray() | ||
{ | ||
AddNumberToBuffer(); | ||
return Numbers.ToArray(); | ||
} | ||
|
||
private void AddNumberToBuffer() | ||
{ | ||
Numbers.Add(currentNumber); | ||
currentNumber = 0; | ||
currentNumberLength = 0; | ||
} | ||
|
||
private byte[] ByteToByteArray(byte oneByte) | ||
{ | ||
var bits = new byte[BITS_IN_BYTE]; | ||
for (int i = BITS_IN_BYTE - 1; i >=0; --i) | ||
{ | ||
bits[i] = (byte)(oneByte % 2); | ||
oneByte >>= 1; | ||
} | ||
|
||
return bits; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
delete commented code