473,837 Members | 1,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String to byte array

Is there a routine in c# that will transform a string
ie"Hello Mom" into a
Byte[] array. I have found
char[] cTmp = pString.ToCharA rray();

But I have not been able to figure out how to convert a char into a hex
value and place that value into the byte[].

Thanks for your help

Dan C
Nov 15 '05 #1
11 30587
Dan C <MSN/da********@msn. com> wrote:
Is there a routine in c# that will transform a string
ie"Hello Mom" into a
Byte[] array. I have found
char[] cTmp = pString.ToCharA rray();

But I have not been able to figure out how to convert a char into a hex
value and place that value into the byte[].


Don't forget that a char is 16 bits, so you'd need two bytes to
represent a char in the simple way.

Normally converting a string to a byte array is done using an Encoding
though.

See http://www.pobox.com/~skeet/csharp/unicode.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
"Dan C" <MSN/da********@msn. com> wrote
Is there a routine in c# that will transform a string
ie"Hello Mom" into a
Byte[] array. I have found
char[] cTmp = pString.ToCharA rray();

But I have not been able to figure out how to convert a char into a hex
value and place that value into the byte[].

Here is a routine I used to convert a string called mPassword to a byte
array:
//Set your string here:
string mPassword = "Hello Mom";

//create the byte[] array here:
byte[] Bytstr = new byte[mPassword.Lengt h];

//convert the string to a byte array here:
System.Text.Enc oding.ASCII.Get Bytes(mPassword .ToCharArray(), 0,mPassword.Len g
th,Bytstr,0);

//for debugging, read the values of each byte from the string in the array:
byte myByte;
string[] tmpBytStr = new string[mPassword.Lengt h];
for(int i = 0; i<mPassword.Len gth;i++)
{
myByte = Bytstr[i];
tmpBytStr[i] = myByte.ToString ();
}

Hope this is what you were looking for :)

--
Brian L. Gorman
Nov 15 '05 #3
Brian L. Gorman <bl******@hotma il.com> wrote:
//Set your string here:
string mPassword = "Hello Mom";

//create the byte[] array here:
byte[] Bytstr = new byte[mPassword.Lengt h];

//convert the string to a byte array here:
System.Text.Enc oding.ASCII.Get Bytes(mPassword .ToCharArray(), 0,mPassword.Len g
th,Bytstr,0);


That's a very long-winded way of doing it. Why not just use:

byte[] Bytstr = Encoding.ASCII. GetBytes (mPassword);

? It does the same thing, but rather more simply (and readably).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
Or use unmanaged code and map the byte array over the char array. I think
that's fastest.
{
char[] charArray = {'c','b','a'};

byte* pByteArray;

fixed(char* pCharArray = charArray)

{

pByteArray = (byte*)(pCharAr ray);

}
}
--
you'll have pByteArray pointing to the byte array.
Horatiu Ripa

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Brian L. Gorman <bl******@hotma il.com> wrote:
//Set your string here:
string mPassword = "Hello Mom";

//create the byte[] array here:
byte[] Bytstr = new byte[mPassword.Lengt h];

//convert the string to a byte array here:
System.Text.Enc oding.ASCII.Get Bytes(mPassword .ToCharArray(), 0,mPassword.Len g th,Bytstr,0);


That's a very long-winded way of doing it. Why not just use:

byte[] Bytstr = Encoding.ASCII. GetBytes (mPassword);

? It does the same thing, but rather more simply (and readably).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #5
Horatiu Ripa <un****@busines sco.us> wrote:
Or use unmanaged code and map the byte array over the char array. I think
that's fastest.
{
char[] charArray = {'c','b','a'};

byte* pByteArray;

fixed(char* pCharArray = charArray)

{

pByteArray = (byte*)(pCharAr ray);

}
}


Quick correction: that's not unmanaged code, it's unsafe code. It also
doesn't really convert it to a byte array - you could use it within the
unsafe method, but it's not like you can use it elsewhere. It also
assumes a UTF-16 encoding, which may not be what's wanted.

I'd stick with safe code and Encoding.GetByt es, myself.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
:) unsafe, of course, the rush... Agree, it cannot be used outside unsafe
scope and assumes UTF-16 but is way much faster on very large volumes of
data. When you have to map a structure over the content of a binary file
that contains something like "records" = structure and "fields" = structure
members , considering that there's no type transformations you have to made,
and you want to consume in high speed the data, or to produce data through a
structure in binary files this approach is way faster (I have a specific
implementation where I've used it and the results were that it worked more
than 10 times faster).
Of course within the limitations you've underlined.
But in usual applications I prefer also avoiding unsafe (and unmanaged :)
too) code. By the way, I would surely like to see the structures having a
ToByteArray and a FromByteArray implemented...

--
Horatiu Ripa

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Horatiu Ripa <un****@busines sco.us> wrote:
Or use unmanaged code and map the byte array over the char array. I think that's fastest.
{
char[] charArray = {'c','b','a'};

byte* pByteArray;

fixed(char* pCharArray = charArray)

{

pByteArray = (byte*)(pCharAr ray);

}
}


Quick correction: that's not unmanaged code, it's unsafe code. It also
doesn't really convert it to a byte array - you could use it within the
unsafe method, but it's not like you can use it elsewhere. It also
assumes a UTF-16 encoding, which may not be what's wanted.

I'd stick with safe code and Encoding.GetByt es, myself.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #7
Horatiu Ripa <un****@busines sco.us> wrote:
:) unsafe, of course, the rush... Agree, it cannot be used outside unsafe
scope and assumes UTF-16 but is way much faster on very large volumes of
data. When you have to map a structure over the content of a binary file
that contains something like "records" = structure and "fields" = structure
members , considering that there's no type transformations you have to made,
and you want to consume in high speed the data, or to produce data through a
structure in binary files this approach is way faster (I have a specific
implementation where I've used it and the results were that it worked more
than 10 times faster).


Did you try using the other alternative of Buffer.BlockCop y? That would
involve making a copy of the data, but should still be very fast, and
wouldn't involve unsafe code.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
Hmmm...
I don't think that I can fully use that in my specific case but I have to
take a good thought about that.
Thanks for the hint.

--
Horatiu Ripa
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Horatiu Ripa <un****@busines sco.us> wrote:
:) unsafe, of course, the rush... Agree, it cannot be used outside unsafe scope and assumes UTF-16 but is way much faster on very large volumes of
data. When you have to map a structure over the content of a binary file
that contains something like "records" = structure and "fields" = structure members , considering that there's no type transformations you have to made, and you want to consume in high speed the data, or to produce data through a structure in binary files this approach is way faster (I have a specific
implementation where I've used it and the results were that it worked more than 10 times faster).


Did you try using the other alternative of Buffer.BlockCop y? That would
involve making a copy of the data, but should still be very fast, and
wouldn't involve unsafe code.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #9
This is almost what I need. Unfortunately instead of "Hello" as decimal 72,
101, 108, 108, 111 I need the values in hex. this would be 48, 65, 6C, 6C,
6F.
I think that these values will still fit in the byte array.

Thanks.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Brian L. Gorman <bl******@hotma il.com> wrote:
//Set your string here:
string mPassword = "Hello Mom";

//create the byte[] array here:
byte[] Bytstr = new byte[mPassword.Lengt h];

//convert the string to a byte array here:
System.Text.Enc oding.ASCII.Get Bytes(mPassword .ToCharArray(), 0,mPassword.Len g th,Bytstr,0);


That's a very long-winded way of doing it. Why not just use:

byte[] Bytstr = Encoding.ASCII. GetBytes (mPassword);

? It does the same thing, but rather more simply (and readably).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #10

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

Similar topics

4
8833
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where a * occurs in the string). This split function should allocate a 2D array of chars and put the split results in different rows. The listing below shows how I started to work on this. To keep the program simple and help focus the program the...
6
10248
by: Ricardo Quintanilla | last post by:
i have a code that sends data to a socket listening over as400 platform, the socket responds to me as a "byte array". then i need to convert the "byte array" into a string. the problem is that the data converted from the byte array into a string , is not what i expect. example: - the data returned from the socket is (byte array) "Usuario Sin Atribuciones Para Esta Función"
4
13416
by: David Bargna | last post by:
Hi I have a problem, I have a string which needs to be converted to a byte array, then have the string representation of this array stored in an AD attribute. This string attribute then has to be read and the string representation of the byte array has to be converted back to the original byte array and converted back to the original string - confused yet? in psuedo
9
7138
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but when I tried the program on the Win98 system it will be running on, I get the following error: Cast from string "2076719" to type 'Long' is not valid I am not sure why I only get this error on the Win98 system or how to go about correcting...
2
3597
by: Bryan | last post by:
Apologies if this is a noob question, but I've been struggling with this for quite a while... I'm trying to convert a byte array (encrypted authorization code) into a *screen-printable* string that is displayed in a text box. Once displayed, the text will be copied, transmitted and then pasted (all manually by humans) into a second utility where the string must then be reverse-engineered into the *original* byte array. The byte array will...
8
4210
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...
6
53735
by: moondaddy | last post by:
I'm writing an app in vb.net 1.1 and need to convert a byte array into a string, and then from a string back to a byte array. for example Private mByte() as New Byte(4){11,22,33,44} Now how do I convert it to: dim myStr as string = "11,22,33,44"
4
3400
by: ThunderMusic | last post by:
Hi, I have to go from Byte() to String, do some processing then reconvert the String to byte() but using ascii format, not unicode. I currently use a stream to write the char() (BinaryWriter.Write) from the string (String.ToCharArray), then use Stream.ToArray to convert everything to byte(). It works most of the time, but it happens that an error tells me something like "Additional information: Caractère de substitution faible trouvé...
5
4855
by: da1978 | last post by:
Hi experts, I need to convert a string or a Byte array to a string byte array. Its relatively easy to convert a string to an char array or a byte array but not a STRING byte array. i.e. Dim Array() As Char Dim strwork As String = "76A3kj9d6" Array = strwork.ToCharArray OR
0
10875
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10566
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...
0
10272
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
9401
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
7806
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
7001
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5848
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4474
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
3124
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.