Введение
Тип кодовой системы
A prefix code is a type of code system distinguished by its possession of the "prefix property", which requires that there is no whole code word in the system that is a prefix (initial segment) of any other code word in the system. It is trivially true for fixed length code, so only a point of consideration in variable length code. For example, a code with code words {9, 55} has the prefix property; a code consisting of {9, 5, 59, 55} does not, because "5" is a prefix of "59" and also of "55". A prefix code is a uniquely decodable code: given a complete and accurate sequence, a receiver can identify each word without requiring a special marker between words. However, there are uniquely decodable codes that are not prefix codes; for instance, the reverse of a prefix code is still uniquely decodable (it is a suffix code), but it is not necessarily a prefix code. Prefix codes are also known as prefix free codes, prefix condition codes and instantaneous codes. Although Huffman coding is just one of many algorithms for deriving prefix codes, prefix codes are also widely referred to as "Huffman codes", even when the code was not produced by a Huffman algorithm. The term comma free code is sometimes also applied as a synonym for prefix free codes but in most mathematical books and articles (e. g.) a comma free code is used to mean a self synchronizing code, a subclass of prefix codes. Using prefix codes, a message can be transmitted as a sequence of concatenated code words, without any out of band markers or (alternatively) special markers between words to frame the words in the message. The recipient can decode the message unambiguously, by repeatedly finding and removing sequences that form valid code words. This is not generally possible with codes that lack the prefix property, for example {0, 1, 10, 11}: a receiver reading a "1" at the start of a code word would not know whether that was the complete code word "1", or merely the prefix of the code word "10" or "11"; so the string "10" could be interpreted either as a single codeword or as the concatenation of the words "1" then "0". The variable length Huffman codes, country calling codes, the country and publisher parts of ISBNs, the Secondary Synchronization Codes used in the UMTS W CDMA 3G Wireless Standard, and the instruction sets (machine language) of most computer microarchitectures are prefix codes. Prefix codes are not error correcting codes. In practice, a message might first be compressed with a prefix code, and then encoded again with channel coding (including error correction) before transmission. For any uniquely decodable code there is a prefix code that has the same code word lengths. Kraft's inequality characterizes the sets of code word lengths that are possible in a uniquely decodable code.
Код префикса — это тип кодовой системы, отличающийся наличием "свойства префикса", которое требует, чтобы в системе не было целого кодового слова, являющегося префиксом (начальным сегментом) любого другого кодового слова в системе. Это тривиально верно для кодов фиксированной длины, поэтому это важно учитывать только в кодах переменной длины. Например, код с кодовыми словами {9, 55} обладает свойством префикса; код, состоящий из {9, 5, 59, 55}, — нет, потому что "5" является префиксом "59" и также "55". Код префикса — это однозначно декодируемый код: при получении полной и точной последовательности приемник может идентифицировать каждое слово без необходимости использования специального разделителя между словами. Однако существуют однозначно декодируемые коды, которые не являются кодами префикса; например, обратный код префикса все еще однозначно декодируем (это код суффикса), но он не обязательно является кодом префикса. Коды префиксов также известны как коды без префиксов, коды с условием префикса и мгновенные коды. Хотя кодирование Хаффмана — это лишь один из многих алгоритмов для получения кодов префикса, коды префикса также часто называют "кодами Хаффмана", даже если код не был получен с помощью алгоритма Хаффмана. Термин "код без разделителей" иногда также используется как синоним кодов без префиксов, но в большинстве математических книг и статей (например) код без разделителей используется для обозначения самосинхронизирующегося кода, подкласса кодов префиксов.
A prefix code is a type of code system distinguished by its possession of the "prefix property", which requires that there is no whole code word in the system that is a prefix (initial segment) of any other code word in the system. It is trivially true for fixed length code, so only a point of consideration in variable length code. For example, a code with code words {9, 55} has the prefix property; a code consisting of {9, 5, 59, 55} does not, because "5" is a prefix of "59" and also of "55". A prefix code is a uniquely decodable code: given a complete and accurate sequence, a receiver can identify each word without requiring a special marker between words. However, there are uniquely decodable codes that are not prefix codes; for instance, the reverse of a prefix code is still uniquely decodable (it is a suffix code), but it is not necessarily a prefix code. Prefix codes are also known as prefix free codes, prefix condition codes and instantaneous codes. Although Huffman coding is just one of many algorithms for deriving prefix codes, prefix codes are also widely referred to as "Huffman codes", even when the code was not produced by a Huffman algorithm. The term comma free code is sometimes also applied as a synonym for prefix free codes but in most mathematical books and articles (e. g.) a comma free code is used to mean a self synchronizing code, a subclass of prefix codes. Using prefix codes, a message can be transmitted as a sequence of concatenated code words, without any out of band markers or (alternatively) special markers between words to frame the words in the message. The recipient can decode the message unambiguously, by repeatedly finding and removing sequences that form valid code words. This is not generally possible with codes that lack the prefix property, for example {0, 1, 10, 11}: a receiver reading a "1" at the start of a code word would not know whether that was the complete code word "1", or merely the prefix of the code word "10" or "11"; so the string "10" could be interpreted either as a single codeword or as the concatenation of the words "1" then "0". The variable length Huffman codes, country calling codes, the country and publisher parts of ISBNs, the Secondary Synchronization Codes used in the UMTS W CDMA 3G Wireless Standard, and the instruction sets (machine language) of most computer microarchitectures are prefix codes. Prefix codes are not error correcting codes. In practice, a message might first be compressed with a prefix code, and then encoded again with channel coding (including error correction) before transmission. For any uniquely decodable code there is a prefix code that has the same code word lengths. Kraft's inequality characterizes the sets of code word lengths that are possible in a uniquely decodable code.
Используя коды префиксов, сообщение можно передавать как последовательность конкатенированных кодовых слов без каких-либо дополнительных маркеров или (в качестве альтернативы) специальных разделителей между словами для выделения слов в сообщении. Приемник может однозначно декодировать сообщение, многократно находя и удаляя последовательности, образующие допустимые кодовые слова. Это не всегда возможно с кодами, не обладающими свойством префикса, например {0, 1, 10, 11}: приемник, считывающий "1" в начале кодового слова, не будет знать, является ли это полным кодовым словом "1" или просто префиксом кодового слова "10" или "11"; следовательно, строку "10" можно интерпретировать либо как одно кодовое слово, либо как конкатенацию слов "1", а затем "0".
A prefix code is a type of code system distinguished by its possession of the "prefix property", which requires that there is no whole code word in the system that is a prefix (initial segment) of any other code word in the system. It is trivially true for fixed length code, so only a point of consideration in variable length code. For example, a code with code words {9, 55} has the prefix property; a code consisting of {9, 5, 59, 55} does not, because "5" is a prefix of "59" and also of "55". A prefix code is a uniquely decodable code: given a complete and accurate sequence, a receiver can identify each word without requiring a special marker between words. However, there are uniquely decodable codes that are not prefix codes; for instance, the reverse of a prefix code is still uniquely decodable (it is a suffix code), but it is not necessarily a prefix code. Prefix codes are also known as prefix free codes, prefix condition codes and instantaneous codes. Although Huffman coding is just one of many algorithms for deriving prefix codes, prefix codes are also widely referred to as "Huffman codes", even when the code was not produced by a Huffman algorithm. The term comma free code is sometimes also applied as a synonym for prefix free codes but in most mathematical books and articles (e. g.) a comma free code is used to mean a self synchronizing code, a subclass of prefix codes. Using prefix codes, a message can be transmitted as a sequence of concatenated code words, without any out of band markers or (alternatively) special markers between words to frame the words in the message. The recipient can decode the message unambiguously, by repeatedly finding and removing sequences that form valid code words. This is not generally possible with codes that lack the prefix property, for example {0, 1, 10, 11}: a receiver reading a "1" at the start of a code word would not know whether that was the complete code word "1", or merely the prefix of the code word "10" or "11"; so the string "10" could be interpreted either as a single codeword or as the concatenation of the words "1" then "0". The variable length Huffman codes, country calling codes, the country and publisher parts of ISBNs, the Secondary Synchronization Codes used in the UMTS W CDMA 3G Wireless Standard, and the instruction sets (machine language) of most computer microarchitectures are prefix codes. Prefix codes are not error correcting codes. In practice, a message might first be compressed with a prefix code, and then encoded again with channel coding (including error correction) before transmission. For any uniquely decodable code there is a prefix code that has the same code word lengths. Kraft's inequality characterizes the sets of code word lengths that are possible in a uniquely decodable code.
Коды Хаффмана переменной длины, коды вызова стран, части ISBN, содержащие информацию о стране и издателе, коды вторичной синхронизации, используемые в стандарте UMTS W-CDMA 3G Wireless, и наборы инструкций (машинный код) большинства компьютерных микроархитектур являются кодами префиксов. Коды префиксов не являются кодами коррекции ошибок. На практике сообщение может быть сначала сжато с помощью кода префикса, а затем снова закодировано с использованием кодирования канала (включая коррекцию ошибок) перед передачей. Для любого однозначно декодируемого кода существует код префикса с той же длиной кодовых слов. Неравенство Крафта характеризует множества длин кодовых слов, которые возможны в однозначно декодируемом коде.
A prefix code is a type of code system distinguished by its possession of the "prefix property", which requires that there is no whole code word in the system that is a prefix (initial segment) of any other code word in the system. It is trivially true for fixed length code, so only a point of consideration in variable length code. For example, a code with code words {9, 55} has the prefix property; a code consisting of {9, 5, 59, 55} does not, because "5" is a prefix of "59" and also of "55". A prefix code is a uniquely decodable code: given a complete and accurate sequence, a receiver can identify each word without requiring a special marker between words. However, there are uniquely decodable codes that are not prefix codes; for instance, the reverse of a prefix code is still uniquely decodable (it is a suffix code), but it is not necessarily a prefix code. Prefix codes are also known as prefix free codes, prefix condition codes and instantaneous codes. Although Huffman coding is just one of many algorithms for deriving prefix codes, prefix codes are also widely referred to as "Huffman codes", even when the code was not produced by a Huffman algorithm. The term comma free code is sometimes also applied as a synonym for prefix free codes but in most mathematical books and articles (e. g.) a comma free code is used to mean a self synchronizing code, a subclass of prefix codes. Using prefix codes, a message can be transmitted as a sequence of concatenated code words, without any out of band markers or (alternatively) special markers between words to frame the words in the message. The recipient can decode the message unambiguously, by repeatedly finding and removing sequences that form valid code words. This is not generally possible with codes that lack the prefix property, for example {0, 1, 10, 11}: a receiver reading a "1" at the start of a code word would not know whether that was the complete code word "1", or merely the prefix of the code word "10" or "11"; so the string "10" could be interpreted either as a single codeword or as the concatenation of the words "1" then "0". The variable length Huffman codes, country calling codes, the country and publisher parts of ISBNs, the Secondary Synchronization Codes used in the UMTS W CDMA 3G Wireless Standard, and the instruction sets (machine language) of most computer microarchitectures are prefix codes. Prefix codes are not error correcting codes. In practice, a message might first be compressed with a prefix code, and then encoded again with channel coding (including error correction) before transmission. For any uniquely decodable code there is a prefix code that has the same code word lengths. Kraft's inequality characterizes the sets of code word lengths that are possible in a uniquely decodable code.
Техника
Если каждое слово в коде имеет одинаковую длину, код называется кодом фиксированной длины или блочным кодом (хотя термин блочный код также используется для кодов коррекции ошибок фиксированного размера в кодировании каналов). Например, символы ISO 8859-15 всегда имеют длину 8 бит. Символы UTF-32/UCS-4 всегда имеют длину 32 бита. Ячейки ATM всегда имеют длину 424 бита (53 байта). Код фиксированной длины с фиксированной длиной k битов может кодировать до исходных символов. Код фиксированной длины обязательно является префиксным кодом. Любой код можно преобразовать в код фиксированной длины, дополняя более короткие префиксы фиксированными символами, чтобы соответствовать длине самых длинных префиксов. Альтернативно, такие коды дополнения могут использоваться для введения избыточности, обеспечивающей автокоррекцию и/или синхронизацию. Однако кодирование фиксированной длины неэффективно в ситуациях, когда некоторые слова с большей вероятностью будут передаваться, чем другие. Усеченное двоичное кодирование является прямым обобщением кодов фиксированной длины для случаев, когда число символов n не является степенью двойки. Символам источника присваиваются кодовые слова длины k и k+1, где k выбирается таким образом, чтобы 2k < n ≤ 2k+1. Кодирование Хаффмана — более сложный метод построения префиксных кодов переменной длины. Алгоритм кодирования Хаффмана принимает в качестве входных данных частоты, которые должны иметь кодовые слова, и создает префиксный код, который минимизирует средневзвешенную длину кодовых слов. (Это тесно связано с минимизацией энтропии.) Это форма сжатия данных без потерь, основанная на энтропийном кодировании. Некоторые коды отмечают конец кодового слова специальным символом "разделитель" (также называемым сигнальным значением), отличным от обычных данных. Это несколько аналогично пробелам между словами в предложении; они обозначают, где заканчивается одно слово и начинается другое. Если каждое кодовое слово заканчивается разделителем, и разделитель не встречается в другом месте в кодовом слове, код автоматически является префиксным. Однако резервирование целого символа только для использования в качестве разделителя может быть неэффективным, особенно для языков с небольшим количеством символов. Код Морзе — это повседневный пример кода переменной длины с разделителем. Длинные паузы между буквами и еще более длинные паузы между словами помогают людям распознать, где заканчивается одна буква (или слово) и начинается следующая. Аналогично, кодирование Фибоначчи использует "11" для обозначения конца каждого кодового слова. Самосинхронизирующиеся коды — это префиксные коды, которые позволяют осуществлять синхронизацию кадров.
Связанные понятия
Код суффиксов — это набор слов, ни одно из которых не является суффиксом другого; эквивалентно, набор слов, являющихся обратными к коду префиксов. Как и в случае с кодом префиксов, представление строки в виде конкатенации таких слов является однозначным. Бификс-код — это набор слов, который одновременно является кодом префиксов и кодом суффиксов. Оптимальный код префиксов — это код префиксов с минимальной средней длиной. То есть, предположим алфавит из n символов с вероятностями для кода префиксов C. Если C' — другой код префиксов, а — длины кодовых слов C', то .