Encoding.ASCII.GetString()

  • Thread starter Thread starter devgrt
  • Start date Start date
D

devgrt

C#:
I have a buffer that is populated with char data from a DLL:
byte [] ret = new byte[1024];
I want to convert to a C# string:
string msg = Encoding.ASCII.GetString(ret, 0, ret.Length);

The problem is I never know in advance what size the string will be. When I
call Encoding.ASCII.GetString I need to specify the size. If I set it to
ret.Length as above then in the debugger I can see msg is the full 1024
bytes (0 padded at the end regardless of the actual string's size).
How can I look at a byte[] and determine the size of the string in it (I
know I could just loop and look for the first occurance of 0 -- is tha tthe
best way?)

Thank you!
 
Hello, devgrt!

d> The problem is I never know in advance what size the string will be.
d> When I call Encoding.ASCII.GetString I need to specify the size. If I
d> set it to ret.Length as above then in the debugger I can see msg is the
d> full 1024 bytes (0 padded at the end regardless of the actual string's
d> size). How can I look at a byte[] and determine the size of the string
d> in it (I know I could just loop and look for the first occurance of 0 --
d> is tha tthe best way?)

You can use Encoding.ASCII.GetCharCount();
However, why do you need to know the size of the string int the byte[]?

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 
Thank you for reply!
The reason I need to know the length is that I need to specify it in:
string msg = Encoding.ASCII.GetString();
if I say string msg = Encoding.ASCII.GetString(ret, 0, ret.Length); then if
I look at my string msg in debug it is ret.Length and is zero-padded to the
end. If I do msg.Length I always get the ret.Length as opposed to the actual
size of teh string in msg. msg is still useable since it is zero-padded so
MessageBox.Show(msg) works OK but I dont want to waste the space by having
msg larger than it needs to be.
 
You didn't get it right...

in Encoding.ASCII.GetString(....) you specify the length of the buffer and not the length of the string...

then if
I look at my string msg in debug it is ret.Length and is zero-padded to the
end. If I do msg.Length I always get the ret.Length

That is true for ASCII encoding ( every char is equal to 1 byte ), but if you will consider Unicode string ( 1 char is equal to 2 bytes ) then this will break your asumptions...

Internally Encoding.GetString() checks how much symbols of specified encoding are there in the buffer, and creates string that has the same number of symbols ( no waste here ).

You can use Encoding.....GetString() and fear nothing :8-)

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
 
Back
Top