开发者

Appending Bytes puts spaces

开发者 https://www.devze.com 2023-04-09 21:03 出处:网络
I\'m trying to loop through an array of byte and copy the contents to a new list of bytes, and display them back. please see the code below.

I'm trying to loop through an array of byte and copy the contents to a new list of bytes, and display them back. please see the code below.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim myByte() As开发者_如何学Python Byte = New Byte() {65, 66, 67}
    Dim newByte() As Byte = New Byte() {}
    Dim tempByteList As New List(Of Byte)
    For i As Integer = 0 To 2
        ReDim newByte(1)
        Array.Copy(myByte, i, newByte, 0, 1)
        tempByteList.AddRange(newByte)
    Next
    Dim str1 As String = System.Text.UnicodeEncoding.UTF8.GetString(tempByteList.ToArray())
 End Sub

I want to see str1 as "ABC" but the out put i get is "A B C" (ie with spaces between letters) Please note: I have to copy(chunks) within a loop and get the result at the end, this is just a sample to reproduce my real issue.

any help will be appreciated


The problem is in your ReDim statement. Microsoft's definition of ReDim states that the array bounds specified always go from 0 to the bound specified (in your case 1), so you are essentially ReDim-ing a 2 item array, which is why you're seeing "spaces" in between the A, B, and C elements. Change your ReDim statement to

ReDim newByte(0)

and all should be well as you will then be declaring the newByte array to go from 0 to 0 (a single item array), which is what you want.


You could also use the Array.CreateInstance method in VB.Net and not need to do the redim as createInstance makes it exactly the size that you specify. (Only other thing is do you need to build your TempByteList or do you know at the start of the loop the size you require, because you could just create your Final bytearray initially and Array.Copy them into the correct offset rather than append to a list then .ToArray()

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim myByte() As Byte = New Byte() {65, 66, 67}
    Dim newByte() As Byte = CType(Array.CreateInstance(GetType(Byte), 1), Byte())
    Dim tempByteList As New List(Of Byte)
    For i As Integer = 0 To 2
        Array.Copy(myByte, i, newByte, 0, 1)
        tempByteList.AddRange(newByte)
    Next
    Dim str1 As String = System.Text.UnicodeEncoding.UTF8.GetString(tempByteList.ToArray())
End Sub
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号