How to implement Baudot encoding

2019-08-09 00:55发布

I'm trying to implement a Baudot character encoding (a 6 bit per character code) in .Net. It's for a Cospas Sarsat device.

I've started by deriving from the Encoding class:

public class BaudotEncoding : Encoding {

I'm looking for a simple, efficient way to implement a bidirectional character map (the map can be readonly):

Dictionary<char, int> CharacterMap = new Dictionary<char, int> {
    { ' ', 0x100100 },
    { '-', 0x011000 },
    { '/', 0x010111 },
    { '0', 0x001101 },
    { '1', 0x011101 },
    { '2', 0x011001 },
    ...
}

I also need to figure out how to implement the GetBytes method of System.Text.Encoding

public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) {

I am having trouble figuring out how to implement this method because the characters don't fit in nice 8 bit sets.

1条回答
Summer. ? 凉城
2楼-- · 2019-08-09 01:42

Simple string constants may be sufficient for the mapping of chars to int values, and possibly faster than Dictionary. This quickly thrown together code shows the idea of what I was describing in your previous question. I don't know how you want to handle the figures/letters issue, and you'd want to add range checking on arguments. You'll also need to test for correctness. But it shows the idea of just putting the char values in a string and using that to look up in both directions. Given an int value, it will be as fast as you can get. Given a char to do the reverse lookup will, I expect, be extremely fast as well.

public class Baudot {
    public const char Null = 'n';
    public const char ShiftToFigures = 'f';
    public const char ShiftToLetters = 'l';
    public const char Undefined = 'u';
    public const char Wru = 'w';
    public const char Bell = 'b';
    private const string Letters = "nE\nA SIU\rDRJNFCKTZLWHYPQOBGfMXVu";
    private const string Figures = "n3\n- b87\rw4',!:(5\")2#6019?&u./;l";

    public static char? GetFigure(int key) {
        char? c = Figures[key];
        return (c != Undefined) ? c : null;
    }

    public static int? GetFigure(char c) {
        int? i = Figures.IndexOf(c);
        return (i >= 0) ? i : null;
    }

    public static char? GetLetter(int key) {
        char? c = Letters[key];
        return (c != Undefined) ? c : null;
    }

    public static int? GetLetter(char c) {
        int? i = Letters.IndexOf(c);
        return (i >= 0) ? i : null;
    }
}

You will also probably want to modify the simple handling of special characters I define as constants. For example, using char(0) for null, ASCII bell for bell (if there is such a thing). I just threw in quick lowercase letters for demonstration purposes.

I used nullable return values to demonstrate the notion of not finding something. But it might be simpler to just return the Undefined constant if a given int value does not map to anything, and -1 if the given char is not in the Baudot character set.

查看更多
登录 后发表回答