473,786 Members | 2,567 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

byte[] to string conversion ...

This is the code snippet that I've come up to convert a byte[]
to string. Is there a best practiced method for such a conversion?

- Jamie

public static string ByteArrayToStri ng(byte[] array)
{
if (null == array || 0 == array.Length)
{
throw new NullReferenceEx ception();
return null;
}
else
{
Encoding ascii = Encoding.ASCII;
char[] asciiChars =
new char[ascii.GetCharCo unt(array, 0, array.Length)];
string str = null;

ascii.GetChars( array, 0, array.Length, asciiChars, 0);

foreach (string s in (new string(asciiCha rs)).Split('\n' ))
{
if (str != null) str += Environment.New Line;
str += s.Trim();
}
return str;
}
}
Nov 23 '06 #1
5 9042
This is the code snippet that I've come up to convert a byte[]
to string. Is there a best practiced method for such a conversion?
public static string ByteArrayToStri ng(byte[] array)
return System.Text.ASC IIEncoding.ASCI I.GetString(arr ay);
}

--
Pozdrav,
Josip Medved
http://www.jmedved.com

Nov 23 '06 #2
Hi Jamie,

System.Encoding has already the appropriate methods:

public static string ByteArrayToStri ng(byte[] array)
{
if (array == null)
{
throw new ArgumentNullExc eption("array") ;
}
return Encoding.ASCII. GetString(array );
}

public static byte[] StringToByteArr ay(string value)
{
if (value == null)
{
throw new ArgumentNullExc eption("array") ;
}
return Encoding.ASCII. GetBytes(value) ;
}

Best Regards,

Wiebe Tijsma
http://www.e-office.com

Jamie Risk wrote:
This is the code snippet that I've come up to convert a byte[] to
string. Is there a best practiced method for such a conversion?

- Jamie

public static string ByteArrayToStri ng(byte[] array)
{
if (null == array || 0 == array.Length)
{
throw new NullReferenceEx ception();
return null;
}
else
{
Encoding ascii = Encoding.ASCII;
char[] asciiChars =
new char[ascii.GetCharCo unt(array, 0, array.Length)];
string str = null;

ascii.GetChars( array, 0, array.Length, asciiChars, 0);

foreach (string s in (new string(asciiCha rs)).Split('\n' ))
{
if (str != null) str += Environment.New Line;
str += s.Trim();
}
return str;
}
}
Nov 23 '06 #3
Jamie Risk <risk.#.@intect us.comwrote:
This is the code snippet that I've come up to convert a byte[]
to string. Is there a best practiced method for such a conversion?
Well, for a start the easiest way of doing the first part of your work
is to call Encoding.ASCII. GetString(array ) instead of going through
GetCharCount, GetChars and new string(...).

Now, it looks like the rest of your conversion is to trim each line,
and then glue them back together using Environment.New Line - correct?

If so, I'd use String.Split to get the array, then call Trim on each
element, then call String.Join to join them back together again
afterwards.

By the way, I don't *believe* String.Split will ever return a null
element.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '06 #4
Jamie Risk wrote:
This is the code snippet that I've come up to convert a byte[] to
string. Is there a best practiced method for such a conversion?
public static string ByteArrayToStri ng(byte[] array)
{
if (null == array || 0 == array.Length)
{
throw new NullReferenceEx ception();
return null;
}
else
{
Encoding ascii = Encoding.ASCII;
char[] asciiChars =
new char[ascii.GetCharCo unt(array, 0, array.Length)];
string str = null;

ascii.GetChars( array, 0, array.Length, asciiChars, 0);

foreach (string s in (new string(asciiCha rs)).Split('\n' ))
{
if (str != null) str += Environment.New Line;
str += s.Trim();
}
return str;
}
}
What does the code do that:

ascii.GetString (b)

or maybe

ascii.GetString (b).Replace(@"\ n", Environment.New Line)

does not ?

I guess it trim trailing space of lines, but is that really
needed.

If you need the trimming then maybe a simple for loop
copying from one byte array to another and a ascii.GetString
on the new array.

Arne

Nov 23 '06 #5
Wiebe Tijsma <wi*********@ca pitalstijsma.co mwrote:
Hi Jamie,

System.Encoding has already the appropriate methods:

public static string ByteArrayToStri ng(byte[] array)
{
if (array == null)
{
throw new ArgumentNullExc eption("array") ;
}
return Encoding.ASCII. GetString(array );
}
"zeros" will get you in trouble. Base64 is probably what you are looking for
if you intend to transfer a byte array as a string.

--
Thomas T. Veldhouse
Key Fingerprint: D281 77A5 63EE 82C5 5E68 00E4 7868 0ADC 4EFB 39F0
Nov 27 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
7924
by: Bryan Parkoff | last post by:
I have two variables: "char A" and "short B". I can be able to convert from A to B using explicit case conversion with no problem like "B = short (A);". Right now, I have two variables: "char T" and "short A". T has an array of six elements. I desire to capture first element and second element as two bytes into word as short. The problem is that "A" captures only one element instead of two elements. I have looked at machine language...
43
4821
by: Bill Cunningham | last post by:
I've been reading the C standard online and I'm puzzled as to what multibyte chars are. Wide chars I believe would be characters for languages such as cantonese or Japanese. I know the ASCII character set specifies that each character such as 'b' or 'B' is an 8 bit character. So what's a multibyte character? Also how would you use the function parameter main (char argc, char **argv) if that's correct? Bill
4
2438
by: Dennis Myrén | last post by:
Hi. Is there a way to utilize the great primitive data type formatting routines available in .NET without working with strings? I want a byte directly rather than a string. I think it is unfortunate that i have to walk via System.String to do that. For instance, from an integer of value 123, i want:
3
276693
by: pkumar | last post by:
How to convert this byte array to string byte b=new byte; Is there any function or I need read one by one and build the string thanks
25
7306
by: Charles Law | last post by:
I thought this was going to be straight forward, given the wealth of conversion functions in .NET, but it is proving more convoluted than imagined. Given the following <code> Dim ba(1) As Byte Dim b As Byte
8
4206
by: moondaddy | last post by:
I need to convert a byte array to a string and pass it as a parameter in a URL and then convert it back to the original byte array. However, its getting scrambled in the conversion. In short, here's the code: ====================================== Dim textConverter As New ASCIIEncoding Dim sParam As String = "This is my cool param" Dim bytParam() As Byte 'load the byte array here...
11
5280
by: chaitali.pats | last post by:
Hi , I have implemented MD5 in C language . I am getting an output of 32 bits Hexadecimal number . for example : 83a80d3ca057492f0ce99ac1db8dced0 I need to convert this string same to 16 byte array. Can anyone help me ?
16
2155
by: Hugh Janus | last post by:
Hi all, I am using the below functions in order to convert strings to bytes and vice versa. I totally ans shamefully stole these functions from this group btw! Anyway, they work great but as sooooo slow. Anyone know how I can speed this functions up? I basically need to convert a byte to string, perform a function on each 'section' of the string, then reconvert it to a byte. The slow part is the conversion to and from byte, not the...
5
5973
by: jeremyje | last post by:
I'm writing some code that will convert a regular string to a byte for compression and then beable to convert that compressed string back into original form. Conceptually I have.... For compression string ->(Unicode Conversion) byte -(Compression + Unicode Conversion) string
0
9497
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8992
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7515
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4067
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.