So I need to convert a hex string on my server which could contain any byte number from 0-255 into a byte to send it to my client.

This works fine in most situations, but when converting to a byte with any hex between the range of 0x80 and 0x9F it gets switched out for 0x3F (using the Encoding.GetBytes() function on the string).

I understand this is an encoding problem, and currently I'm using the default encoding (which is Windows-1252 in my area). So my question is what encoding could I use to be able to encode all 255 bytes?

It's very important I can send and receive all the bytes correctly without them being converted to 0x3F, as the server handles up to 255 clients which are all assigned a client number as a byte, so if the client number is for example 135 (0x87), it gets sent as 63 (0x3F) which is obviously a big error.

Recommended Answers

All 4 Replies

Where are you getting this string from? If it's from a MySQL database, why not just store it as a byte array in a blob? Alternatively, you could roll your own string -> byte array converter very easily:

List<byte> temp = new List<byte>();

foreach (char c in yourString)

var yourByteArray = temp.ToArray<byte>();

ASCIIEncoding might be what you need.
Is the following the sort of thing you are doing?

byte[] bytes = new byte[] { 0x87, 0x31, 0x32, 0x33 };
string test = ASCIIEncoding.ASCII.GetString(bytes);

^ Yup, specifically:

Byte[] ToSendByte = Settings.Encoder.GetBytes(ToSend);

                    // Send the bytes
                    ClientSocket.BeginSend(ToSendByte, 0, ToSendByte.Length, SocketFlags.None, new AsyncCallback(SendFinish), null);

ToSend is a String variable which is the packet to send to the client. Using System.Text.Encoding.GetEncoding(1252) (Windows-1252) worked fine except it converts everything between 0x80 and 0x9F to 0x3F.

I tried ASCII but that converts everything above 127 (anything 8bit) to 0x3F - Thanks for the suggestion though. Basically I need an encoding type that can encode all 255 bytes without swapping any of them for 0x3F or something.

@Yamachi - The string isn't from a MySQL database, and I tried your method of manually converting the byte and it works fine except in my test it converted 0x87 to 0x2021 which is pretty much putting me back where I started (unable to convert between 0x80 and 0x9F).



This encoding allows the use of 0x80 -> 0x9F. Thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.