how to get the specify items in byte() array in VB - vb.net

I am working on the VB.NET. I have two arrays need to compare and output the remainder of the longer array. I just simplify my question as following code:
Dim array1 As Byte() = {&H01, &H22,&H10,&HBC,&HA2,&H01,&H00,&HA6,&H02,&HBB,&H33,&H11,&HB2,&H01}
Dim array As Byte() = {&H01, &H22,&H10,&HBC,&HA2,&H01,&H00,&HA6,&H02,&HBB,&H33,&H11,&HB2,&H02,&H77,&H44,&HBF}
Dim remainder As Byte()
IF(array1.Length< array2.Length) then
Dim remainderLength = array2.Length- array1.Length
For...
'''array1.Length =14
'''array2.Length =17
'''write the code to sign the last 3 Hex values into new array remainder and output the remainder
Next
the remainder length might be changed to other sizes, 100, 200 or more. I tried the Item()function and IndexOf()function, and didn't get the result. Please help to write the left code. The final result I want remainder = {&H77,&H44,&HBF}
thank you very much for any comments.

The simplest approach would be to use LINQ's Skip extension method.
For Each b As Byte In array.Skip(array1.Length)
Console.Write(b)
Next
Or:
Dim remainder As Byte() = array.Skip(array1.Length).ToArray()
You may also want to consider using the Array.Copy method which allows you to pass the starting index as an argument:
Array.Copy(array, array1.Length, remainder, 0, array.Length - array1.Length)
Or, if all else fails, it's always possible to access each item in the array by index:
For i As Integer = array1.Length to array.Length
Console.Write(array(i))
Next

Related

Change byte array to integer in VB.net

I have a byte array need to convert to integer, and this array only have one value. I tried Bitconverter, convert.ToInt32 both are not working for me. my code as follows:
Dim a As new Byte() ={&H1C} ' the value range is {&H01} to {&HFF}
Dim key As integer = BitConverter.ToInt32(a,1)
I need the result with key = 28, which convert function I should use?
Thank you very much.
BitConverter.ToInt32 needs 4 bytes to work with, so you just need to put your one byte value into a 4 byte array. Allowing for the endianness, something like this:
Dim a() As Byte = { &H1C }
Dim b(3) As Byte
If BitConverter.IsLittleEndian Then
b(0) = a(0)
Else
b(3) = a(0)
End If
Dim key As Integer = BitConverter.ToInt32(b, 0)
You are not converting an array of values, but rather a single array element.
That said, there is no need to call a conversion function to convert a single Byte to an Integer. Just assign the value.
Dim key As Integer = a(0)

How to read HDF5 bytes array resulting of string dataset

I use the HDF5DotNet libraries with VB.net. I need to read a string dataset (3000 items, each item len = 16).
I use a byte array to store all the values but it's not easy to parse : I need to get a string by line and not a part of string. Do you know a better way to store and parse the result ?
Here my code:
'Load the file
Dim HDF5TestFileID As HDF5DotNet.H5FileId
HDF5TestFileID = H5F.open("C:\test.hdf5", H5F.OpenMode.ACC_RDONLY)
'Get datset and group id
Dim GroupRootId As HDF5DotNet.H5GroupId = H5G.open(HDF5TestFileID, "/")
Dim dataSetRN As H5DataSetId = H5D.open(GroupRootId, "MyItemsNames")
'Build byte array from the dataset
Dim readDataBackRN(16 * 3000) As Byte
Dim h5DataBackRN As New H5Array(Of Byte)(readDataBackRN)
Dim typeIdRN As H5DataTypeId = H5D.GetType(dataSetRN)
H5D.read(dataSetRN, typeIdRN, h5DataBackRN)
'try to parse the result but not easy to use data
Dim content as string = System.Text.Encoding.UTF8.GetString(readDataBackRN).Replace(" ", "<br>")
You normally read the buffer, check if the string is complete and if not continue reading and append the new contents to the previous fragment and keep doing that until you find the end of line.
Can you do this?
In this case the string is complete but it's possible that one day I reach the limit of size. I cannot modify the H5D.read method. I wonder if an simple array of byte is the best way ?
The better way would be to store result in a an array of array of bytes (1 array of byte per line of string) and not store all items in a single array of bytes ?
But I don't knwon if it's possible.

build an array of integers inside a for next loop vb.net

i got this far ... my data string, "num_str" contains a set of ~10 numbers, each separated by a comma. the last part of the string is a blank entry, so i use '.Trim' to avoid an error
Dim i As Integer
Dim m_data() As String
m_data = num_str.Split(",")
For i = 0 To UBound(m_data)
If m_data(i).Trim.Length > 0 Then
MsgBox(Convert.ToInt32(m_data(i).Trim))
End If
Next i
as you can see from the Msgbox, each of the numbers successfully pass through the loop.
where i am stuck is how to place all of the 'Convert.ToInt32(m_data(i).Trim)' numbers, which are now presumably integers, into an array.
how do i build an array of integers inside the For / Next loop so i can find MAX and MIN and LAST
TIA
You just need to initialize the array with the zero-based indexer. You can deduce it's initial size from the size of the string():
Dim m_data = num_str.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Dim intArray(m_data.Length) As Int32
For i = 0 To m_data.Length - 1
intArray(i) = Int32.Parse(m_data(i).Trim())
Next i
Note that i've also used the overload of String.Split which removes empty strings.
This way is more concise using the Select LINQ Operator.
Dim arrayOfInts = num_str.
Split({","c},
StringSplitOptions.RemoveEmptyEntries).
Select(Function(v) Int32.Parse(v.Trim()))
Dim minInt = arrayOfInts.Min()
Dim maxint = arrayOfInts.Max()

VB.NET - Array of Integers needs to be instantiated, how to?

First try
Dim holdValues() As Integer 'Doesn't Work
holdValues(1) = 55
Second try
Dim holdValues(-1) As Integer 'Gives me Index was outside the bounds of the array.
holdValues(1) = 55
I'm trying to do something similar to
Dim myString(-1) As String
But apparently this doesn't apply to integer arrays. I don't know what the size of the array will be, it wont get smaller but it will grow larger.
Any help will be appreciated, thank you!
You could use the Initializers shortcut:
Dim myValues As Integer() = New Integer() {55, 56, 67}
But if you want to resize the array, etc. then definately have a look at a List(Of Integer):
'Initialise the list
Dim myValues As New System.Collections.Generic.List(Of Integer)
'Shortcut to pre-populate it with known values
myValues.AddRange(New Integer() {55, 56, 57})
'Add a new value, dynamically resizing the array
myValues.Add(32)
'It probably has a method do do what you want, but if you really need an array:
myValues.ToArray()
you add the number to
holdValues(x) //x+1 will be size of array
so something like this
Dim array(2) As Integer
array(0) = 100
array(1) = 10
array(2) = 1
you can re-allocate the array to be bigger if needed by doing this.
ReDim array(10) as Integer
you'll have to add in your code when you should make your array bigger. You can also look into lists. Lists take care of this issue automatically.
here's some info on Lists: http://www.dotnetperls.com/list-vbnet
Hope this helps.
Also a link for general knowledge on arrays http://www.dotnetperls.com/array-vbnet

Fastest way to detect duplicate numbers on array vb.net 2005

I have this project that let user inputs 5 different numbers from 1 to 50. But I want to validate it before saving to DB that i will be 5 unique numbers. What's the best and fastest way to do this?
You can use HashSet(Of T) to check this:
Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
Dim hash As HashSet(Of Integer) = new HashSet(Of Integer)(numbers)
Dim unique As Boolean = hash.Count = numbers.Count()
This will be much more efficient than options requiring a sort + iteration.
Check this code
Private Function HasDuplicates(ByVal arr As Array) As Boolean
For i As Integer = 0 To arr.Length - 1
If Not arr(i) Is Nothing Then
Dim l As Integer = Array.LastIndexOf(arr, arr(i))
If l <> i Then Return True
End If
Next
Return False
End Function
Reed Copsey's suggestion to use hash sets was a good one (I hadn't worked with the HashSet class before).
But I then discovered that the IEnumerable class offers an extension method called Distinct that copies the unique values from a source IEnumerable to a target IEnumerable.
Borrowing the first line of Reed's sample code, here's the new sample VB.NET code:
Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
Dim isUnique As Boolean = (numbers.Distinct.Count = numbers.Count)
The variable isUnique is True if the numbers IEnumerable contains no duplicate values, or False if it contains one or more duplicate values.
Put in an array, sort it and check if elements 1,2 2,3 3,4 and 4,5 are different (in a loop).
Pseudocode:
integer numbers[50]
zeroarray(numbers, 50)
integer count = 0;
while (count < 5)
{
integer value = getinput()
if (value >= 1 and value <= 50)
if (numbers[value] = 0)
{
count = count + 1
numbers[value] = 1
}
else
reject duplicate
else
reject invalid
}
You can try this very simple method:
Filtering Arrays using LINQ
To simplifiy lets say the user inputs 5 different numbers from 0 to 49.
You can create a Boolean Array IsUsed(49) with 50 elements.
Then when the user input the value iInputNum=30 you can set IsUsed(30)=TRUE.
Next time, when the user input the second value iInputNum=7, you can set IsUsed(7)=TRUE
In this way you can check in a very fast way if the number was already inserted.
if IsUsed(iInputNum) then
'Skip the Input (put the right code here)
else
'Accept the number
IsUsed(iInputNum)=TRUE
'save iInputNum in the database
end if
Do not forget to clear the array after inserting all 5 numbers.
Remenber to put the right index in order to handle the number 1-50 (e not 0-49)
Here's an alternate solution, not sure how it compares, efficiency wise, to the other solutions, but it seems to work (uses LINQ).
Dim numbers As List<int> = getListOfNumbers()
Dim allUnique As Boolean = numbers.Distinct().Count() = numbers.Count()
Very late to the party, but what about something like this (C#, sorry)?
byte[] hits = new byte[51];
byte[] entries = new byte[] { 1, 12, 12, 32, 26, 49 };
foreach (var entry in entries)
{
hits[entry]++;
}
The elements in the hits array are automatically initialized to 0. When the foreach loop is complete, hits will contain the occurrence count for every number in entries. If any is greater than 1, you have dupes.