1

I want to append two bytes to one byte using VB.NET

This is my code,

Dim bytes(5) As Byte
bytes(0) = devid 'variable byte
bytes(1) = &H3
bytes(2) = x1 'variable byte
bytes(3) = x2 'variable byte
bytes(4) = &H0
bytes(5) = &H1

Dim bytescrc() As Byte = CRC(bytes) ' call to crc funtion and store 2 bytes output is { &HFF, &HB5 }

Dim bytesful() As Byte = {bytes, bytescrc}

Error msg is Value of type 'Byte()' cannot be converted to 'Byte'.

How to append bytes 6 byte array and bytescrc 2 byte array to bytesful byte array.

2 Answers 2

7

There are a number of specific ways this could be done but a little LINQ makes it easy:

Dim bytesful() As Byte = bytes.Concat(bytescrc).ToArray()

Concat will create a single IEnumerable(Of T) by concatenating two IEnumerable(Of T) objects and ToArray creates a new array from that single list.

Sign up to request clarification or add additional context in comments.

Comments

7

Adding the Array.CopyTo() method to the one proposed by jmcilhinney, in case performace is something to consider.
In the case presented it wouldn't matter, but should the number of elements increase (in thousands) and the operation iterated, the result could be quite different.

Dim bytesful((bytes.Length + bytescrc.Length) - 1) As Byte

bytes.CopyTo(bytesful, 0)
bytescrc.CopyTo(bytesful, bytes.Length)

Enumerable.Concat() has the advantage that it's more readable an you can add even more arrays in one single line:

Dim bytesful() As Byte = bytes.Concat(bytescrc).Concat(SomethingElse).ToArray()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.