468,470 Members | 2,108 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,470 developers. It's quick & easy.

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
Br,
Shadab Ahmad
Mar 18 '11 #1
3 13200
yarbrough40
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
!NoItAll
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
  2.  
  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
  8.  
  9. End Function
  10.  
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
  4.  
Mar 20 '11 #3
!NoItAll
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 NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.