|
-
January 6th, 2010, 11:51 PM
#1
[RESOLVED] byte [] and string
Hi ;
a simple question I hope.
Can data in a byte array be held in a string object without any possible issue regarding the limitaion that string class may have dealing with binary data?
Cheers
-
January 7th, 2010, 12:28 AM
#2
Re: byte [] and string
Yes, depending upon the encoding of the data, you can use System.Text encoding utilities. Following assumes the ASCII encoding.
Code:
using System;
using System.Text;
public class Me
{
public static void Main(string[] args)
{
byte[] bdata = new byte[] {0x30, 0x31, 0x32, 0x01, 0x39}; // some gibberish in the middle
string str = Encoding.ASCII.GetString(bdata);
Console.WriteLine(str);
}
}
The encoding ignores the unprintable characters.
-
January 7th, 2010, 12:33 AM
#3
Re: byte [] and string
ascii encoding is limited to a signed byte (7 bits instead of the full 8). use System.ConvertTo/FromBase64String
-
January 7th, 2010, 12:35 AM
#4
Re: byte [] and string
If Encoding ignores the unprintable characters , what this means is some of the data would be lost when they are moved to the string objext is not it?
then teh answer woudl be NO i guess to my question.
is this what you meant:
Code:
string base64String;
try {
base64String =
System.Convert.ToBase64String(binaryData,
0,
binaryData.Length);
}
catch (System.ArgumentNullException) {
System.Console.WriteLine("Binary data array is null.");
return;
}
Last edited by Saeed; January 7th, 2010 at 12:48 AM.
-
January 7th, 2010, 01:08 AM
#5
Re: byte [] and string
.net strings are 16 bit arrays, so they are capable of storing a byte array of any size without issue. The only time you run into issues is when you encode it using a schema that is limited (such as ascii) or if you need to be able to print the contents of the string (non-printable characters).
if you were to translate it directly into a string (appending each byte as a character in the string) you would be able to store each byte into the string, but wouldn't be able to print the string. base 64 encoding (much like encoding your bytes to their hex equiv.) allows you to actually print and see the byte array within the printable character subset.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|