简体   繁体   中英

How do you convert a string to 7-bit ASCII with even parity?

I need to convert a string to 7-bit ASCII with even parity in a C# application which communicates with a mainframe. I tried using Encoding.ASCII , however, it does not have the correct parity.

You will have to calculate the parity bit yourself. So:

  1. convert string into byte array using built in 8bit ASCII encoding. Most top bit should allways be 0 using this encoding.
  2. do the bit modifications on each byte and set parity bit for each byte.

There is no built-in functionality for calculating parity bit, that I know of.

Perhaps something like this:

public static byte[] StringTo7bitAsciiEvenParity(string text)
{
    byte[] bytes = Encoding.ASCII.GetBytes(text);

    for(int i = 0; i < bytes.Length; i++)
    {
        if(((((bytes[i] * 0x0101010101010101UL) & 0x8040201008040201UL) % 0x1FF) & 1) == 0)
        {
            bytes[i] &= 0x7F;
        }
        else
        {
            bytes[i] |= 0x80;
        }
    }
    return bytes;
}

Completely untested. Don't ask me how the magic to compute parity works. I just found it here . But some variant of this should do what you want.

I tried to make this work for the case ',' becoming 0x82. But I can't work out how that is supposed to be done. ',' is, in ASCII, binary 00101100 and 0x82 is binary 10000010. I don't see the correlation at all.

Assuming byte-level parity and no-endian related behavior (ie a stream of bytes), the following works as intended (tested against a known 7-bit ASCII even parity table ):

public static byte[] GetAsciiBytesEvenParity(this string text)
{
    byte[] bytes = Encoding.ASCII.GetBytes(text);

    for(int ii = 0; ii < bytes.Length; ii++)
    {
        // parity test adapted from: 
        // http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel
        if (((0x6996 >> ((bytes[ii] ^ (bytes[ii] >> 4)) & 0xf)) & 1) != 0)
        {
            bytes[ii] |= 0x80;
        }
    }

    return bytes;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM