could you explain why?

  • Thread starter Thread starter David Wang
  • Start date Start date
D

David Wang

HI,
Please look at following code example:
string convert2string(byte [] bys)
{
string string1 = Encoding.ASCII.GetString(bys, 0, 30).TrimEnd(null);

return string1;
}

byte [] allzero = new byte [40];
string dbstr = convert2string(byte);

After I get dbstr(which is empty), I write it to SQL database. When I read
this from database again, and serilize to XML message, I see
..... which means dbstr actually was not empty,
it filled with all "0" inside. Can anybody explain why? How can I get rid of
it? Thank you.

David
 
string convert2string(byte [] bys)
{
string string1 = Encoding.ASCII.GetString(bys, 0, 30).TrimEnd(null);

return string1;
}

byte [] allzero = new byte [40];
string dbstr = convert2string(byte);
TYPO: I think you mean convert2string(allzero)
After I get dbstr(which is empty),
It is NOT empty... Just because it has non-printable characters
doesn't make it empty.
If you do:
Console.WriteLine("Length is: " + dbstr.Length);

You'll find it has 30 characters (I assume all are ASCII code 0).
byte [] allzero = new byte [40];
creates an array of value-types. So you have 40 bytes, each with a
default value of 0.

I suspect you'll want to add a check in convert2string to look for
all-zero case and return "" instead.

HTH,
Mike
 
David Wang said:
Please look at following code example:
string convert2string(byte [] bys)
{
string string1 = Encoding.ASCII.GetString(bys, 0, 30).TrimEnd(null);

return string1;
}

byte [] allzero = new byte [40];
string dbstr = convert2string(byte);

After I get dbstr(which is empty), I write it to SQL database. When I read
this from database again, and serilize to XML message, I see
..... which means dbstr actually was not empty,
it filled with all "0" inside. Can anybody explain why? How can I get rid of
it? Thank you.

Instead of calling TrimEnd (null) which will do nothing, call
TrimEnd ('\0')
 
Back
Top