.Net 8-bit Encoding -


i'm working on serial port, transmitting , receiving data hardware @ 8bit data. store string facilitate comparison, , preset data stored string or hex format in xml file. found out when using encoding.default ansi encoding 8bit data converted , reversible. ascii encoding works 7bit data, , utf8 or utf7 doesn't works too, since i'm using character 1-255. encoding.default fine, read on msdn it's dependent on os codepage setting, means might behave differently on different codepage configured. use getbytes() , getstring extensively using encoding, failsafe , portable method works time @ configuration. idea or better suggestion this?

latin-1 aka iso-8859-1 aka codepage 28591 useful codepage scenario, maps values in range 128-255 unchanged. following interchangeable:

encoding.getencoding(28591) encoding.getencoding("latin1") encoding.getencoding("iso-8859-1") 

the following code illustrates fact latin1, unlike encoding.default, characters in range 0-255 mapped unchanged:

static void main(string[] args) {      console.writeline("test default encoding returned {0}", testencoding(encoding.default));     console.writeline("test latin1 encoding returned {0}", testencoding(encoding.getencoding("latin1")));     console.readline();     return; }  private static bool comparebytes(char[] chars, byte[] bytes) {     bool result = true;     if (chars.length != bytes.length)     {         console.writeline("length mismatch {0} bytes , {1} chars" + bytes.length, chars.length);         return false;     }     (int = 0; < chars.length; i++)     {         int charvalue = (int)chars[i];         if (charvalue != (int)bytes[i])         {             console.writeline("byte @ index {0} value {1:x4} not match char {2:x4}", i, (int) bytes[i], charvalue);             result = false;         }     }     return result; } private static bool testencoding(encoding encoding) {     byte[] inputbytes = new byte[256];     (int = 0; < 256; i++)     {         inputbytes[i] = (byte) i;     }      char[] outputchars = encoding.getchars(inputbytes);     console.writeline("comparing input bytes , output chars");     if (!comparebytes(outputchars, inputbytes)) return false;      byte[] outputbytes = encoding.getbytes(outputchars);     console.writeline("comparing output bytes , output chars");     if (!comparebytes(outputchars, outputbytes)) return false;      return true; } 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -