473,594 Members | 2,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

convert string to byte array

Trying to convert string to byte array.

the following code returns byte array of {107, 62, 194, 139, 64}

how can I convert this string to a byte array of {107, 62, 139, 65}

System.Text.UTF 8Encoding str = new System.Text.UTF 8Encoding();

string s = new string((char)10 7, 1);
s += new string((char)62 , 1);
s += new string((char)13 9, 1);
s += new string((char)65 , 1);

byte[] binScanData = str.GetBytes(s) ;

Thanks
Peter
Sep 16 '08 #1
12 13527
On Sep 16, 5:59*am, "Peter" <czu...@nospam. nospamwrote:
Trying to convert string to byte array.

the following code returns byte array of {107, 62, 194, 139, 64}
No it doesn't - the last byte is 65, not 64. The reason why you get
194 and 139 is due to how UTF-8 encoding works.
how can I convert this string to a byte array of {107, 62, 139, 65}
You could use ISO-8859-1 (Encoding.GetEn coding(28591)).

However, if you're trying to encode arbitrary opaque binary data in a
string, I *strongly* recommend using base64 instead.

Jon
Sep 16 '08 #2
Peter wrote:
Trying to convert string to byte array.

the following code returns byte array of {107, 62, 194, 139, 64}

how can I convert this string to a byte array of {107, 62, 139, 65}

System.Text.UTF 8Encoding str = new System.Text.UTF 8Encoding();

string s = new string((char)10 7, 1);
s += new string((char)62 , 1);
s += new string((char)13 9, 1);
s += new string((char)65 , 1);

byte[] binScanData = str.GetBytes(s) ;

Thanks
Peter
I don't think you can (or should) convert that to a byte array of {107,
62, 139, 65}

what you are doing is concatenating 4 /unicode/ chars together, what
you really should be decoding to is a unicode byte array, but that
won't give you what you want, it will give you what you are encoding
though ;-)

System.Text.Uni codeEncoding str = new System.Text.Uni codeEncoding();
string s = new string((char)10 7, 1);
s += new string((char)62 , 1);
s += new string((char)13 9, 1);
s += new string((char)65 , 1);

byte[] binScanData = str.GetBytes(s) ;

and this will give you the /correct/ result...i.e.
{107,0,62,0,139 ,0,65,0}

Rgds Tim.

--

Sep 16 '08 #3
Have a look at BitConverter, specifically the ToSingle Method.
Sep 16 '08 #4
Dear Peter,

The code use should returns byte array of {107,62,139,65} , this is because
139 is greater than 127, the UTF-8 encoding uses two bytes to reprent it.

However, to retrieve the array you need, you can do something like this:

char[] cs = s.ToCharArray() ;
byte[] binScanData = new byte[cs.Length];
for(int j =0;j<cs.Length; j++)
{
binScanData[j] = (byte)cs[j];
}

Should you have any questions, please feel free to let me know.

Sincerely,
Zhi-Xin Ye
Microsoft Managed Newsgroup Support Team

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsof t.com.

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subs...#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/...tance&ln=en-us.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 16 '08 #5
Zhi-Xin Ye [MSFT] wrote:
Dear Peter,

The code use should returns byte array of {107,62,139,65} , this is
because 139 is greater than 127, the UTF-8 encoding uses two bytes to
reprent it.

However, to retrieve the array you need, you can do something like
this:

char[] cs = s.ToCharArray() ;
byte[] binScanData = new byte[cs.Length];
for(int j =0;j<cs.Length; j++)
{
binScanData[j] = (byte)cs[j];
}
The problem is though with this solution and also with Jon's is that
although it will work with the original posters char type casts of
107,62,139,65 if any value greater than 255 is cast, say (char)500,
both solutions will lose information. The bottom line is that a char
and a byte simply do not occupy the same storage space therefore
comparing a char array and a byte array are like comparing apples and
oranges.
Sep 16 '08 #6
Tim Jarvis <ti*@jarvis.com .auwrote:
The problem is though with this solution and also with Jon's is that
although it will work with the original posters char type casts of
107,62,139,65 if any value greater than 255 is cast, say (char)500,
both solutions will lose information. The bottom line is that a char
and a byte simply do not occupy the same storage space therefore
comparing a char array and a byte array are like comparing apples and
oranges.
Absolutely. There are additional oddities involved in terms of
combining characters etc which may not be preserved - that's why I
always use Base64 to encode arbitrary binary data as text.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 17 '08 #7

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
Tim Jarvis <ti*@jarvis.com .auwrote:
>The problem is though with this solution and also with Jon's is that
although it will work with the original posters char type casts of
107,62,139,6 5 if any value greater than 255 is cast, say (char)500,
both solutions will lose information. The bottom line is that a char
and a byte simply do not occupy the same storage space therefore
comparing a char array and a byte array are like comparing apples and
oranges.

Absolutely. There are additional oddities involved in terms of
combining characters etc which may not be preserved - that's why I
always use Base64 to encode arbitrary binary data as text.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
The char array is actually a an array of floats stored as one long string in
the database, so in this case each char will never be more then 255.
The float array was moved in memory from the float array into string using
VB6 and CopyMemory Win32 API and stored in a database. I am trying to
retrieve it and convert it back to float array using C#. The data is stored
in Access database in a memo field, so I can't retrieve it as byte[] array,
I have to retrieve it as a string and somehow move it to float array.


Sep 18 '08 #8
Peter <cz****@nospam. nospamwrote:
The char array is actually a an array of floats stored as one long string in
the database, so in this case each char will never be more then 255.
The float array was moved in memory from the float array into string using
VB6 and CopyMemory Win32 API and stored in a database. I am trying to
retrieve it and convert it back to float array using C#. The data is stored
in Access database in a memo field, so I can't retrieve it as byte[] array,
I have to retrieve it as a string and somehow move it to float array.
Okay, the first thing to realise is that this scheme is *incredibly*
brittle. If you get the chance, do migrate away from it.

I don't know how Access handles Unicode, but that's likely to have a
significant impact on how you retrieve the data - in particular which
encoding you need to specify. If you believe that after fetching from
Access into a .NET string each character accurately represents one byte
with the trivial mapping (i.e. unicode char x for byte x) then using
Encoding.GetEnc oding(28591) should work - or just cast each byte.

It's well worth creating a test record containing every byte, 0-255, so
you can verify that you can read it again.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 18 '08 #9
Jon Skeet [C# MVP] wrote:
Okay, the first thing to realise is that this scheme is incredibly
brittle. If you get the chance, do migrate away from it.
Also hunt down the person responsible and give him a wedgie...

;-)

--

Sep 18 '08 #10

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

Similar topics

13
6100
by: Dan V. | last post by:
How do I create a one line text file with these control codes? e.g.: 144 = 0x90 and 147 = 0x93? I am trying to create a one line text file with these characters all one one row with no spaces. 1. 144 = 0x90 2. 147 = 0x93 3. STX = (^B = 2 = 0x2) 4. NUL = (^@ = 0 = 0x0)
5
18821
by: kevinniu | last post by:
Hi everyone, In c#, what is the fastest way(include unsafe) to convert a array of bytes(which really contains the bytes of a double array) to a arry of double. thanks
6
10168
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"
15
34577
by: Kueishiong Tu | last post by:
How do I convert a Byte array (unsigned char managed) to a char array(unmanaged) with wide character taken into account?
2
9345
by: antonio matos | last post by:
hi people. I have to acess a database, and there are some fields that are binary. when i acess that field is read like an array of bytes. but in reality it's an array of doubles!!! how can i convert from a byte array to a double array?
2
2630
by: Jaime Stuardo | last post by:
Hi all... I'm trying to retrieve a SQLXML query using VB.NET. When I programmed in VB 6.0, I used Stream object to accomplish this which was trivial. I cannot do the same thing in VB.NET. Here the most similar object is the OleDbDataReader. I have the following method, ¿is it correct what I am doing? By doing oRdr.GetBytes(0, 0, bBytes, 0, 1000) I'm limiting only to 1000 bytes. How can I know the length of the stream?
0
4312
by: Jim Rasmussen | last post by:
I need some help in converting a byte array to pdf. Could someone give me an example of how in C#? Here is what I have so far, using System.IO; string sFile = "c:\testpdf.pdf"; FileStream fs = File.Create(sFile); BinaryWriter bw = new BinaryWriter(fs);
5
4840
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
3
11555
by: dpsairam | last post by:
Hi, How to convert a byte array to image....i mean i have to convert a Byte array into image format.....please hellp.........i need the java code... Thanking You.
1
13324
by: phpuser123 | last post by:
I want to convert my object to byte array and then next to an object and run a method..The codes are below: public class test_serialisation implements Serializable{ /** * */ private static final long serialVersionUID = 1L;
0
7874
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
8366
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
7997
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
8227
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
6646
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
5738
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...
1
2383
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
1
1469
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1203
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.