I have a hexadecimal value,
07A5953EE7592CE8871EE287F9C0A5FBC2BB43695589D95E76A4A9D37019C8
Which I want to convert to a byte array.
Is there a built-in function in .NET 3.5 that will get the job done or will I need to write a function to loop through each pair in the string and convert it to its 8-bit integer equivalent?
There is no built-in function that will do this. You will unfortunately have to code one up :(
Public Function ToHexList(ByVal str As String) As List(Of Byte)
Dim list As New List(Of Byte)
For i = 0 to str.Length-1 Step 2
list.Add(Byte.Parse(str.SubString(i,2), Globalization.NumberStyles.HexNumber))
Next
Return list
End Function
EDIT
Qualified the NumberStyles enumeration with the Globalization namespace qualifier. Another option is to import that namespace and remove the qualifier.
I think that you'll find what you are looking for here (codeproject.com)
Related
I'm not real experienced in using Linq, and am trying to understand .ToHashSet.
I'm using VB for this.
I have this code:
' Import the list of Windows Classes to exclude; one per line.
Dim strRead As String = My.Computer.FileSystem.ReadAllText("C:\Exclude.txt")
' Split the string into a string array
Dim strExcludes As String() = strRead.Split(ControlChars.CrLf.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
' Convert the String Array to a HashSet (Traditional Method)
Dim lList As New HashSet(Of String)(strExcludes)
This works as intended; I get each line from the text file into the HashSet as 1 line per Key.
Now, I want to see how to do the same using .ToHashSet. The following code seems to work fine with the exception of it returning as type <Of Char>, so I get each character in it's own Key, rather than each line in it's own Key.
' Convert the String Array to a HashSet (Using System.Linq Method) (Unfinished: Works, but needs to be converted from Char to String)
Dim lListLinq = strRead.ToHashSet()
I've Googled, and fought with it a bit, trying to get it to return as type <Of String>, but not much Google info out there for .ToHashSet for VB, or really much in C# either regarding this particular problem. I'm not seeing where to do the conversion; .ToHashSet itself also accepts no arguments.
Anyone know what I'm missing? I have a feeling it's something real simple slipping by me.
Invoking ToHashSet() on a string will yield a HashSet(Of Char) and will not give the expected result as you've witnessed.
Instead, what you need to do is split the string returned by ReadAllText and then call ToHashSet() on it to get a HashSet(Of String).
strRead.Split(ControlChars.CrLf.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToHashSet()
been playing around with the "left"-function in VBA and noticed that the result is stored as a string. For example:
Left(ws2.range("C2").value,3)
Where ws2 is some worksheet and c2 is some cell in ws2 containing, say, 1234.
The left function would then return "123" but it would be formated as a string. This in turn causes errors for me when i try to access a directories key with this string (which is not possible). I've found a workaround where I :
dim tag as integer
tag = Left(ws2.range("C2").value,3)
This would cause the tag with the value 123 to be stored as an integer which I then can use for accessing the directory.
But i'm wondering if it's possible to modify the "left"-function to return values as integers? or any other format for that matter (long, variant, range, whatever)
Notice that I have figured out a solution but I thought it might be helpful to others and/or a interesting discussion.
For this it is easiest to use Cint() function. There is no need to modify functions, you can always create yours.
The proper way to do it would be to use the Cint() function to cast an expression to an integer.
For details see https://msdn.microsoft.com/en-us/library/fctcwhw9(v=vs.84).aspx
Here are some more conversion functions:
CInt() 'convert to integer
CLng() 'convert to long (long is preferred over integer since integer only has 2 bytes in VBA)
CDbl() 'convert to double
CDec() 'convert to decimal (variable has to be declared as variant)
Made it an answer :)
cint(left(ws2.range("C2").value,3)) would be "better" as you're still relying on VBA to make the conversion for you, also checking the output first to work out if you in fact need to use a long maybe. Also checking the input string is numeric first of all would also be a good check.
using cint
function IntLeft(byval value as string, byval length as integer) as Integer
IntLeft=0 'default if non numeric
if isnumeric(value) then
IntLeft=cint(left(value,length))
end if
end function
using int
function IntLeft(byval value as string, byval length as integer) as Integer
IntLeft=int(left(value,length)) 'int returns the first numbers as an int, 0 if no numbers
end function
You can use Abs function instead to return the left function as integer.
i.e., Abs(Left(ws2.range("C2").value,3))
I am new to VB and have a simple program. I just want the program to display in a message box the number of characters in a long variable. I am using the Len() function. The code is as follows.
Try
Dim num As Long = 1230456985623145
Dim numLength As Long
numLength = Len(num)
MessageBox.Show(numLength.ToString())
Catch ex As Exception
End Try
Simple. However when i run the function, it returns a value of 8 instead of the actual value. Can anyone tell me what i'm doing wrong. Do i need to add anything else to obtain the right value
It should be like this:
Dim num As Long = 1230456985623145
Dim numLength As Long
numLength = Len(num.ToString())
MessageBox.Show(numLength.ToString())
If you forgot to use ToString(), Len function returns the number of bytes required to store the variable, which is 8 because a Long variable requires 8 byte to store.
Definition of Len function in MSDN:
Returns an integer containing either the number of characters in a
string or the nominal number of bytes required to store a variable.
In your original code (before your edit):
You use Name as a parameter in your Len function. Since your code is a WinForm, the Name is a property of the Form. Check the value of the Name using:
MessageBox.Show(Name)
String.Length
Using the Length property of a string is more preferable. Like Adrian Wragg said, it's easier to convert your codes between the languages which are supported by .Net (C#, VB and F#).
I'm almost done converting a module from VB6 to VB.NET, but I'm having trouble with the following 2 quotes and am wondering if there's any way to go about this:
Structure AUDINPUTARRAY
bytes(5000) As Byte
End Structure
I'm trying to change that bytes line to: Dim bytes(5000) as Byte
but it's not letting me define the size in a structure.
Here's the second one:
Private i As Integer, j As Integer, msg As String * 200, hWaveIn As integer
I haven't a clue on how to convert: msg As String * 200
you cannot declare an initial size in VB.Net , you can set its size later using Redim statement in constructor or wherever needed
Structure AUDINPUTARRAY
Public bytes() As Byte
Public Sub New(ByVal size As Integer)
ReDim bytes(size) ' set size=5000
End Sub
End Structure
In Visual Basic .NET, you cannot declare a string to have a fixed length unless you use the VBFixedStringAttribute Class attribute in the declaration. The code in the preceding example causes an error.
You declare a string without a length. When your code assigns a value to the string, the length of the value determines the length of the string
see http://msdn.microsoft.com/en-us/library/f47b0zy4%28v=vs.71%29.aspx
. so your declarration will become
Private i As Integer, j As Integer, hWaveIn As Integer
<VBFixedString(200)> Private msg As String
You can do this via attributes
Public Structure <StructLayout(LayoutKind.Sequential)> AUDINPUTARRAY
Public <MarshalAs(UnmanagedType.ByValArray, SizeConst := 5000)>
Bytes() As Byte
End Structure
I would suggest that, while refactoring your code from VB6 to .net, that you take another look at whether you even want to emulate the fixed-length msg As String * 200. If you were counting on the fixed-length string so that you could chop characters off of the end, and still have a 200-character record, that's messy code that depends on a function's side effects.
When we converted from VB6 (a still-ongoing process), it made the intent of the code clearer if we explicitly set the string to a 200-byte block of spaces. Perhaps by declaring:
String msg = String(' ', 200)
(if that's valid in VB.net as well as C#).
I am trying to figure this one out. I saw a link on how to convert a list of ints to a byte array in C#, but I can't get syntax to work out for me in VB.NET.
Stack Overflow question Converting a list of ints to a byte array.
You just need to use the same function, but pass in a double value rather than an integer value.
Dim doubles as New List(Of Double)
doubles.Add(3.14)
doubles.Add(2.614)
Dim bytes() as Byte
bytes = doubles.SelectMany(Function(d) BitConverter.GetBytes(d)).ToArray()