471,075 Members | 988 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

Convert Byte to String in VB.NET

Hi All!

I had tried to search many forums to get this code.

Yes, just for a single line code. But when everything else failed, I decided to write my own. And it is really working good.

Expand|Select|Wrap|Line Numbers
  1.     Private Function Byte2Str(ByVal gByte() As Byte) As String
  2.         Dim X As Integer
  3.         Dim gTmp As String = ""
  4.         For X = 0 To gByte.Length - 1
  5.             gTmp = gTmp & Chr(gByte(X))
  6.         Next
  7.         Return gTmp
  8.     End Function
Shadab Ahmad
Mar 18 '11 #1
3 14247
320 100+
this is easier:
Expand|Select|Wrap|Line Numbers
  1. Dim s as String = System.Text.ASCIIEncoding.ASCII.GetString(gByte)
Mar 20 '11 #2
296 100+
It would work faster if you used a stringbuilder instead of string - otherwise it has to recreate the entire string with each concatenation.

Expand|Select|Wrap|Line Numbers
  1. Private Function Byte2Str(ByVal gByte() As Byte) As String
  3.         Dim gTmp As New System.Text.StringBuilder
  4.         For X as Int32 = 0 To (gByte.Length - 1)
  5.             gTmp.append(Chr(gByte(X)))
  6.         Next
  7.         Return gTmp.ToString
  9. End Function
But here is a way that appears to be even better from experts exchange - try this instead

Expand|Select|Wrap|Line Numbers
  1.    Private Function ByteArrayToString(ByVal ByteArray As Byte()) As String
  2.         Return System.Text.Encoding.Unicode.GetString(ByteArray)
  3.     End Function
Mar 20 '11 #3
296 100+
One problem with using the system.text.encoding method is that it will assume you want the data converted to one of the encoding methods. Raw is not one of the methods available and so you can actually wind up with something you may not expect (unless you really do want ASCII, or Unicode, or UTF8).
AFAIK - if you want it raw then you need to use the looping method.
Jun 5 '11 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Brian | last post: by
7 posts views Thread by Wilfried Mestdagh | last post: by
4 posts views Thread by John Smith | last post: by
4 posts views Thread by Sam | last post: by
5 posts views Thread by EOS | last post: by
15 posts views Thread by Steve | last post: by
6 posts views Thread by Bob Altman | last post: by
reply views Thread by leo001 | last post: by

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.