473,372 Members | 839 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,372 software developers and data experts.

String to Byte & Vice Versa

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 part I am doing in between after conversion.

TIA
Private Function ArrayToString(ByVal bytes() As Byte, Optional ByVal
format As String = Nothing) As String

If bytes.Length = 0 Then Return String.Empty

Dim sb As New System.Text.StringBuilder(bytes.Length * 4)

For Each b As Byte In bytes

sb.Append(b.ToString(format))
sb.Append(","c)

Next

sb.Length -= 1

Return sb.ToString()

End Function

Private Function StringToArray(ByVal s As String, Optional ByVal
style As System.Globalization.NumberStyles = Nothing) As Byte()

If s.Length = 0 Then Return New Byte() {}

Dim values() As String = s.Split(","c)

Dim bytes(values.Length - 1) As Byte

For index As Integer = 0 To values.Length - 1

bytes(index) = Byte.Parse(EncStr, style)
bytes(index) = Byte.Parse(values(index), style)

Next

Return bytes

End Function

Nov 30 '06 #1
16 2114
"Hugh Janus" <my*************@hotmail.comschrieb:
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.
Why not use
'System.Text.Encoding.GetString'/'System.Text.Encoding.GetBytes'?

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Nov 30 '06 #2
Why not use
'System.Text.Encoding.GetString'/'System.Text.Encoding.GetBytes'?
I don't have that so I assume it is in the 2.0 framework. I should
have mentioned that I am using VB 2005. Is there an alternative?

TIA

Nov 30 '06 #3
"Hugh Janus" <my*************@hotmail.comschrieb:
>Why not use
'System.Text.Encoding.GetString'/'System.Text.Encoding.GetBytes'?

I don't have that so I assume it is in the 2.0 framework. I should
have mentioned that I am using VB 2005. Is there an alternative?
Yes, it's available since .NET 1.0. You'll have to specify the encoding you
want to use:

\\\
Imports System.Text
....
Dim s As String = "Hello World"
Dim b() As Byte = Encoding.Unicode.GetBytes(s)
s = Encoding.Unicode.GetString(b)
MsgBox(s)
///

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

Nov 30 '06 #4
>I should have mentioned that I am using VB 2005. Is there an alternative?

Oops. I am using 2003, not 2005.

Nov 30 '06 #5
I am using 2003 too
instead of using class names u just have to use instances (because its
a shared function)

This will compile

I didn't run it ...any way try it

Dim instance As System.Text.Encoding
Dim bytes As Byte()
Dim returnValue As String

returnValue = instance.GetString(bytes)

for more info check this link

http://msdn2.microsoft.com/en-us/library/744y86tc.aspx

Nov 30 '06 #6
"roader" <ro******@gmail.comschrieb:
>I am using 2003 too
instead of using class names u just have to use instances (because its
a shared function)

This will compile

I didn't run it ...any way try it

Dim instance As System.Text.Encoding
Dim bytes As Byte()
Dim returnValue As String

returnValue = instance.GetString(bytes)
.... but it will throw a 'NullReferenceException' at runtime :-).

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 30 '06 #7
This code will work .....
I am sorry i was little lazy...

Dim instance As System.Text.Encoding = System.Text.Encoding.UTF8

Dim returnValue As String
Dim b As Byte() = {&H34, &H56, &HAA, &H55, &HFF}
returnValue = ""

returnValue = instance.GetString(b)
MsgBox(returnValue)
Best of luck

Nov 30 '06 #8
This is done is both vb2005 and vb2003.
Be sure to add the 'System.Text' Reference to your project

Imports System.Text 'Import the text namespace

Public sub ConvertStringToByte(StringToConvert as string)
Dim b() as byte 'A byte array
b = Encoding.GetBytes(StringToConvert)
end sub

'Convert Byte To String

Public Sub CovertByteToString(BytesToConvert() as byte)
Dim s as string 'An empty string
s = Encoding.Text.GetString(BytesToConvert)
end sub

Hope this awnsers your question. Good Luck!


--
--
Thiele Enterprises - The Power Is In Your Hands Now!
--
"Herfried K. Wagner [MVP]" <hi***************@gmx.atwrote in message
news:ex**************@TK2MSFTNGP02.phx.gbl...
"roader" <ro******@gmail.comschrieb:
>I am using 2003 too
instead of using class names u just have to use instances (because its
a shared function)

This will compile

I didn't run it ...any way try it

Dim instance As System.Text.Encoding
Dim bytes As Byte()
Dim returnValue As String

returnValue = instance.GetString(bytes)
.... but it will throw a 'NullReferenceException' at runtime :-).

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 30 '06 #9


"roader" <ro******@gmail.comwrote in message
news:11**********************@l39g2000cwd.googlegr oups.com...
>I am using 2003 too
instead of using class names u just have to use instances (because its
a shared function)
Huh? You have to use instances "because itís a shared function"??? A
shared method means you don't use an instance, you use a class name :)
Although, in VB.Net you can use instance variables to call shared methods
(which I think shouldn't be allowed, but it is)..
>
This will compile

I didn't run it ...any way try it

Dim instance As System.Text.Encoding
Dim bytes As Byte()
Dim returnValue As String

returnValue = instance.GetString(bytes)
Why not just System.Text.Encoding.UTF8.GetString(bytes)?

HTH,
Mythran
Nov 30 '06 #10
Hugh Janus wrote:
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.
<snip>
Private Function ArrayToString(ByVal bytes() As Byte, Optional ByVal
format As String = Nothing) As String
<snip>
>Private Function StringToArray(ByVal s As String, Optional ByVal
style As System.Globalization.NumberStyles = Nothing) As Byte()
<snip>

To what Herfried K. Wagner [MVP] responded:
<snip>
Why not use
'System.Text.Encoding.GetString'/'System.Text.Encoding.GetBytes'?
It seems the OP is trying something different. In other words, given a
byte sequence of, say {100, 120, 200, 1, 2, ...}, the OP needs to
convert it to the string "100,120,200..." and, eventually, back again
to bytes.

The original methods seem ok to me. If you want to speed them up,
though, maybe you'll have to let go the formatting parameters and live
with more simplistic functions. A possible (and radical) approach could
be:

<code>
Function FromString(ByVal Source As String) As Byte()
'converts a string in the format "123,211,0,45...",
'to an array of bytes {123, 211, 0, 45,...}

If Source Is Nothing OrElse Source.Length = 0 Then
Return New Byte() {}
End If

'Counts the number of ","
'to find the number of bytes to convert
'(!)
Dim Count As Integer = 1
For Each C As Char In Source
If C = ","c Then Count += 1
Next

Dim Bytes(0 To Count - 1) As Byte

Dim AscZero As Integer = Asc("0"c)
Dim Value As Byte
Dim Index As Integer

For Each C As Char In Source
'Converts each char to the corresponding byte value
If C <","c Then
Value = CByte(Value * 10 + (Asc(C) - AscZero))
Else
Bytes(Index) = Value
Index += 1
Value = 0
End If
Next
'Saves the last value
Bytes(Index) = Value
Return Bytes
End Function

Function FromBytes(ByVal Source() As Byte) As String
'Converts an array of bytes in a string in the format
'"123,211,0,45...", where 123, 211, 0, etc are the
'bytes from the array

If Source Is Nothing OrElse Source.Length = 0 Then
Return String.Empty
End If

'Assumes each number occupies 3 digits and is comma
'separated. We probably will need less space than this
Dim Chars(0 To Source.Length * 4 - 1) As Char

'Starts from the end of the array
Dim Index As Integer = Chars.Length - 1
Dim AscZero As Integer = Asc("0"c)

'Saves the converted chars from the end to the
'begining of the string
For P As Integer = Source.Length - 1 To 0 Step -1
Dim B As Integer = Source(P)
If B <0 Then
'Manually converts B to string, from right
'to left (i.e. less significant digits first)
Do While B 0
Chars(Index) = Chr(AscZero + B Mod 10)
B \= 10
Index -= 1
Loop
Else
Chars(Index) = "0"c
Index -= 1
End If
Chars(Index) = ","c
Index -= 1
Next
'Advances Index to point to the first digit
Index += 2

Return New String(Chars, Index, Chars.Length - Index)
End Function
</code>

HTH

Regards,

Branco.

Nov 30 '06 #11
"Ryan S. Thiele" <ma*****@verizon.netschrieb:
This is done is both vb2005 and vb2003.
Be sure to add the 'System.Text' Reference to your project
There's no such reference required.

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 30 '06 #12
"roader" <ro******@gmail.comschrieb:
I am sorry i was little lazy...
Well, you took the misleading sample from the documentation, didn't you?

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://dotnet.mvps.org/dotnet/faqs/>
Nov 30 '06 #13
It seems the OP is trying something different. In other words, given a
byte sequence of, say {100, 120, 200, 1, 2, ...}, the OP needs to
convert it to the string "100,120,200..." and, eventually, back again
to bytes.

The original methods seem ok to me. If you want to speed them up,
though, maybe you'll have to let go the formatting parameters and live
with more simplistic functions. A possible (and radical) approach could
be:
Precisely! Basically, I am sending a file over TCP by reading it in
and sending it as a stream. Before sendind, I need to encrypt the
information so I take the byte sequence and convert it to a string
seperated by commas. Whilst building the string, I encrypt each part
first then add it to the string. Then I convert it back to a byte.

Likewise, to decrypt is the same procedure almost. I have it working
but it is so slow. For example, I can send 10mb in about 8 seconds on
the LAN but with encrypting takes about 5 minutes. Any idea how I can
speed up what I have or if there is a faster way to do it? The
slowdown is the conversion, not the encrypting which is almost instant.

TIA

Dec 1 '06 #14

Hugh Janus wrote:
<snip>
Precisely! Basically, I am sending a file over TCP by reading it in
and sending it as a stream. Before sendind, I need to encrypt the
information so I take the byte sequence and convert it to a string
seperated by commas. Whilst building the string, I encrypt each part
first then add it to the string. Then I convert it back to a byte.
<snip>

Why do you need the array of bytes converted to string? Is this a
requirement of your encryption/decryption algorithm?

B.

Dec 1 '06 #15

Branco Medeiros ha escrito:
Hugh Janus wrote:
<snip>
Precisely! Basically, I am sending a file over TCP by reading it in
and sending it as a stream. Before sendind, I need to encrypt the
information so I take the byte sequence and convert it to a string
seperated by commas. Whilst building the string, I encrypt each part
first then add it to the string. Then I convert it back to a byte.
<snip>

Why do you need the array of bytes converted to string? Is this a
requirement of your encryption/decryption algorithm?

B.
Yes.

Dec 5 '06 #16
Hugh Janus wrote:
Why do you need the array of bytes converted to string? Is this a
requirement of your encryption/decryption algorithm?
Yes.
I supose that if you could just pass the raw bytes to encryption it
would really solve the timing problem.

If not, then a much better alternative may be to use
System.Convert.ToBase64String(). It's *really* fast and will even give
you a smmaler string.

To convert the bytes to string you'd use:

TheString = System.Convert.ToBase64String(ByteArray)

And to convert the string back to bytes, it'd be:

ByteArray = System.Convert.FromBase64String(TheString)

In case you don't know, Base64 is the encoding used when you want to
transmit raw bytes through a medium that only deals with ASCII. The
encoded bytes are turned into a string made only of the chars A-Z, a-z,
the digits 0-9 and the symbols '+' and '/'. This string has usually 30%
more chars than the original array byte count.
HTH.

Regards,

Branco.

Dec 6 '06 #17

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

Similar topics

3
by: mailar | last post by:
HI, Can anyone tell me how is a multi_byte to single byte and vice versa conversion done in DB2. It would be great even if someone can tell me how Oracle does it? Oracle already has functions...
7
by: Matthias S. | last post by:
Hi, I had a look at the vast information on encryption in the MSDN and got pretty confused. All I want to do is to encrypt a string into an encrypted string and later decrypt that (encrypted)...
7
by: Eric | last post by:
Hi All, I need to XOR two same-length Strings against each other. I'm assuming that, in order to do so, I'll need to convert each String to a BitArray. Thus, my question is this: is there an...
4
by: Khalique | last post by:
I have built a web service whose purpose is to copy files from a secure place to client machine and vice versa. The problem I am having is perhaps related to permissions and access rights. For...
1
by: Eugene Anthony | last post by:
Private Function BStr2UStr(BStr) 'Byte string to Unicode string conversion Dim lngLoop BStr2UStr = "" For lngLoop = 1 to LenB(BStr) BStr2UStr = BStr2UStr & Chr(AscB(MidB(BStr,lngLoop,1))) Next...
2
yabansu
by: yabansu | last post by:
Hi all, This is my first message! Using C++ standard libraries, I want to convert a string to a byte array and a byte array to the string. How can I do that? I did it in C# .NET as the...
6
yabansu
by: yabansu | last post by:
Hi all, I think most of you probably know the two .NET framework functions, namely Encoding.GetBytes(string) and Encoding.GetString(byte), to convert string into byte array and vice versa. Now,...
4
by: arunfr | last post by:
Hi , I have tried all the methods available to convert byte () to string and vice versa in VBSCRIPT. Function ByteArray2Text(varByteArray) Dim rs Const adLongVarChar = 201 Set rs =...
6
by: Ole | last post by:
I have a class that I wish to convert into a byte array for sending over a serial line and vice versa - how do I do that? Thanks and regards Ole
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.