473,586 Members | 2,495 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 13526
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
6099
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
18820
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)...
15
34576
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
9344
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
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
13321
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;
1
7965
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...
0
8220
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...
0
6617
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...
1
5712
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...
0
5392
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...
0
3838
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1184
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...

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.