2 Replies - 1140 Views - Last Post: 22 September 2011 - 03:54 PM Rate Topic: -----

#1 hazuki   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 22-September 11

Byte array to string (strange behavior)

Posted 22 September 2011 - 12:46 PM

Hi all. I am implementing a MODBUS driver in C#. Bascically, I am trying to dump a bunch of data into a TCP packet to be sent. I have the information that goes in the packet as an array of bytes. I am using a StreamWriter object which has a Write method which takes a String. I want to translate the array of bytes into a String so that I can put it into the Write method and send out a packet.

        public static void sendCommand(Byte[] data)
        {
            sw.Write(Encoding.ASCII.GetChars(data));

        }


where sw is a StreamWriter object.


I have been using the Encoding.ASCII.GetChars(Byte[]) function to convert the byte array into characters. The problem is that some of the elements of by original byte array that have values which are 0x80 or greater get translated into 0x3F! I think this has something to do with casting a byte which is greater than 127 (0x80) into a Char, which is signed. C# clips the value at 127?

Anyway, how would I go about putting raw hex bytes into a string without having this happen?

Thanks in advance!

Is This A Good Question/Topic? 0
  • +

Replies To: Byte array to string (strange behavior)

#2 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Byte array to string (strange behavior)

Posted 22 September 2011 - 01:15 PM

Why bother converting to a string that's going to be read as binary? Skip the StreamWriter and write the bytes directly to the stream.
Was This Post Helpful? 2
  • +
  • -

#3 hazuki   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 22-September 11

Re: Byte array to string (strange behavior)

Posted 22 September 2011 - 03:54 PM

View PostCurtis Rutland, on 22 September 2011 - 01:15 PM, said:

Why bother converting to a string that's going to be read as binary? Skip the StreamWriter and write the bytes directly to the stream.


Ah, I wasn't aware that I could do this. Forgive me, I'm still new to using .NET and C#.

I'll give this a try.
Thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1