How do you convert a string into hexadecimal in VB.NET? - vb.net

How do I convert a string from a textbox into hexadecimal?
I have only found ways in C#. Does VB.NET have the ability to do such a thing? If it can then I'd like to know how to convert string to hex and hex to string.

Dim val As String
val = "10"
Dim hexVal As Integer
hexVal = Convert.ToInt32(val, 16) //16 specifies the base
Console.WriteLine(hexVal)
This will display 16 which is the integer equivalent of the hexadecimal string "10".

You can convert an integer to a hexdecimal number easily by doing:
Convert.ToInt32(15, 16)
And to convert it back to an integer, you can do:
Integer.Parse("15f", System.Globalization.NumberStyles.HexNumber)

Public Function StrToHex(ByRef Data As String) As String
Dim sVal As String
Dim sHex As String = ""
While Data.Length > 0
sVal = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()))
Data = Data.Substring(1, Data.Length - 1)
sHex = sHex & sVal
End While
Return sHex
End Function

Tried and tested code
Create this function by copy pasting it.
Function StringToHex(ByVal text As String) As String
Dim hex As String
For i As Integer = 0 To text.Length - 1
hex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
Next
Return hex
End Function
Use it like this
Debug.WriteLine(StringToHex("sim0n"))
Source

To convert into hexadecimal, use Convert.ToInt32(val, 16). Convert.ToInt32 supports limited bases, 2, 8, 10, and 16.
To convert into any base, use:
Public Shared Function IntToString(value As Integer, baseChars As Char()) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) + result
value = value / targetBase
Loop While value > 0
Return result
End Function
The above function comes from this question. The C# to VB conversion was done using this.

Short and effective expression to display all characters of String s in hexadecimal form can be written using LINQ:
String.Join(" ", s.Select(Function(c) Conversion.Hex(AscW(c)).PadLeft(4, "0")).ToArray()))
Example:
For string ► fix it gives string 25BA 0020 0066 0069 0078.
Enjoy!
Please keep in mind this is Unicode-enabled, returning 4-digit hexadecimal value for every character, because old plain Non-Unicode ASCII is dead and you should no longer rely on it in any application.

In my humble opinion the code of Tilak seems OK, but is not.
The rounding of value / targetBase gives results that are too large.
By using Fix() the resulting integers will be as they should be.
I compliment Tilak for finding such a neat solution for the question.
In the accompanying code I will show how functions like IntToString can be tested easily.
The expected message in the message box is:
The old results are;
0 1 10 101 100 101 1010 1001 1000 1001 1010
0 1 1X 10 11 1XX 1X0 1X1 10X 100 101
0 1 X 1y 10 11 XX Xy X0 X1 XX
0 1 X 1y 1z 10 11 1X Xy Xz X0
The new results are;
0 1 10 11 100 101 110 111 1000 1001 1010
0 1 X 10 11 1X X0 X1 XX 100 101
0 1 X y 10 11 1X 1y X0 X1 XX
0 1 X y z 10 11 1X 1y 1z X0
The new results are better IMHO.
Public Sub test()
Dim numberCharacters As String = "01Xyz"
Dim messageText As String = "The old results are;" & vbNewLine
For loopCount As Integer = 1 To 2
If loopCount = 2 Then messageText &= "The new results are;" & vbNewLine
For baseLength As Integer = 2 To 5
Dim baseCharacters As Char() = _
Strings.Left(numberCharacters, baseLength).ToArray
For integerValue As Integer = 0 To 10
Dim resultText As String = _
Me.IntToString(integerValue, baseCharacters, loopCount = 2)
messageText &= resultText & " "
Next
messageText &= vbNewLine
Next
Next
Call MsgBox(berichtTekst & "The new results are better IMHO.")
End Sub
Public Function IntToString(value As Integer, baseChars As Char(), _
Optional newCode As Boolean = False) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) & result
If newCode Then ' Improved code
value = Fix(value / targetBase)
Else ' Original code
value = value / targetBase
End If
Loop While value > 0
Return result
End Function
Hopefully this will help others.
I have more than 25 years experience as a programmer, mainly in RPG, Cobol, Synon, CL and Basic. I also know some Delphi, Pascal and C#. I am sure I can be a help to this community.
It makes me sad that I cannot comment to answers. Hopefully someone will add me some points, so that I can more easily help others from now on.
Because of this I add my comment to the answer of Tilak, dated may 8, 2012, as an answer. This is the first and hopefully the only time that I resort to this. Sorry for that, but I know no other way.

Related

VB .NET Convert string to array of bytes without converting the characters

I'm trying to split a string of 32 numerical characters into a 16 length Array of Byte and each value has to stay numerical
from "70033023311330000000004195081460" to array {&H_70, &H_03, &H_30, &H_23, ..}
I've tried multiple stuff but each time either it's the conversion that's wrong or I can't find the appropriate combination of functions to implement it.
'it splits but per 1 character only instead of two
str.Select(Function(n) Convert.ToByte(n, 10)).ToArray
'I also tried looping but then the leading zero disappears and the output is a string converted to HEX which is also not what I want.
Function ConvertStringToHexBinary(str As String) As Byte()
Dim arr(15) As Byte
Dim k = 0
For i As Integer = 0 To str.Length - 1
arr(k) = str(i) & str(i + 1)
k += 1
i += 1
Next
Return arr
End Function
Anyone got any suggestion what to do?
G3nt_M3caj's use of LINQ might be.. er.. appealing to the LINQ lovers but it's horrifically inefficient. LINQ is a hammer; not everything is a nail.
This one is about 3 times faster than the LINQ version:
Dim str As String = "70033023311330000000004195081460"
Dim byt(str.Length/2) as Byte
For i = 0 to str.Length - 1 Step 2
byt(i/2) = Convert.ToByte(str.Substring(i, 2))
Next i
And this one, which does it all with math and doesn't do any new stringing at all is just under 3 times faster than the above (making it around 9 times faster than the LINQ version):
Dim str As String = "70033023311330000000004195081460"
Dim byt(str.Length / 2) As Byte
For i = 0 To str.Length - 1
If i Mod 2 = 0 Then
byt(i / 2) = (Convert.ToByte(str(i)) - &H30) * &HA
Else
byt(i / 2) += Convert.ToByte(str(i)) - &H30
End If
Next i
Of the two, I prefer the stringy version because it's easier to read and work out what's going on - another advantage loops approaches often have over a LINQ approach
Do you need something like this?
Dim str As String = "70033023311330000000004195081460"
Dim mBytes() As Byte = str.
Select(Function(x, n) New With {x, n}).
GroupBy(Function(x) x.n \ 2, Function(x) x.x).
Select(Function(y) Convert.ToByte(New String(y.ToArray()), 10)).ToArray

Convert 32-bit signed integer to 64-bit integer while preserving the exact bits

I have a 32-bit value that is stored in the VB.Net type Integer (i.e. Int32.) I am only interested in the bits - not the numerical value. Sometimes the 32nd bit is a one which is interpreted as a negative number. My goal is to reverse the actual bits. My original data is encoded into bits right-to-left (LSB right-most) and is read back in left-to-right (MSB left-most.) I am adapting someone else's code and design. One thought I had was maybe to convert to a long temporarily but I don't know how to do that and preserve the 32nd bit correctly.
Public Shared Function ReverseBits32(ByVal n As Integer) As Integer
Dim result As Integer = 0
For i As Integer = 0 To 32 - 1
result = result * 2 + n Mod 2
n = n >> 1 'n Or 2
Next
Return result
End Function
If you had a method to reverse the bits of a byte you could apply it four times to the bytes of an integer. A little research finds Bit Twiddling Hacks.
Module Module1
Sub ShowBits(a As Integer)
Dim aa = BitConverter.GetBytes(a)
Console.WriteLine(String.Join(" ", aa.Select(Function(b) Convert.ToString(b, 2).PadLeft(8, "0"c))))
End Sub
Function ReverseBits(b As Byte) As Byte
' From https://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits
Dim c = CULng(b)
Return CByte((((c * &H802UL And &H22110UL) Or (c * &H8020UL And &H88440UL)) * &H10101UL >> 16) And &HFFUL)
End Function
Function ReverseBits(a As Integer) As Integer
Dim bb = BitConverter.GetBytes(a)
Dim cc(3) As Byte
For i = 0 To 3
cc(3 - i) = ReverseBits(bb(i))
Next
Return BitConverter.ToInt32(cc, 0)
End Function
Sub Main()
Dim y = -762334566
ShowBits(y)
y = ReverseBits(y)
ShowBits(y)
Console.ReadLine()
End Sub
End Module
Output from test value:
10011010 10110010 10001111 11010010
01001011 11110001 01001101 01011001
I used the "no 64-bit" method because it is written for a language where arithmetic overflow is ignored - the methods using 64-bit operations rely on that but it is not the default for VB.NET.

7 Byte Hex to Dec Conversion

I need to convert 7 byte hexadecimal values in an Excel column to the decimal equivalents in an adjacent column.
I have over 2000 unique values to convert from hexadecimal to decimal.
I got as far as using Excel's hex2bin and then bin2dec formulas.
I found that Excel is rounding up the least significant 4 decimal places.
Example:
7Byte Hex: 0x803277323A8904
Excel Output: 36084284544158000
Correct Decimal Number: 36084284544157956
This is a small variation of Rick Rothstein's code
Function HexToDecs(ByVal HexString As String) As String
Dim X As Integer
Dim BinStr As String
Const BinValues = "0000000100100011010001010110011110001001101010111100110111101111"
If Left$(HexString, 2) Like "&[hH]" Then
HexString = Mid$(HexString, 3)
End If
If Len(HexString) <= 23 Then
For X = 1 To Len(HexString)
BinStr = BinStr & Mid$(BinValues, 4 * Val("&h" & Mid$(HexString, X, 1)) + 1, 4)
Next
HexToDecd = CDec(0)
For X = 0 To Len(BinStr) - 1
HexToDecd = HexToDecd + Val(Mid(BinStr, Len(BinStr) - X, 1)) * 2 ^ X
Next
Else
' Number is too big, handle error here
End If
HexToDecs = CStr(HexToDecd)
End Function
NOTE:
This UDF() returns a String representation of the integer to avoid the 15 digit limitation to true numeric values.
I have elected not to start my input string with 0x
Excel maximum number of digits. In Excel spreadsheet, there is a limit for storing a number in a Cell, which is 15 digits (15 numbers) regardless of whether the numbers are decimal places. Excel call this “15 significant digits of precision” which adheres to “IEEE 754”.Feb 24, 2015
In order to have 36084284544157956, which has 17 digits, save the cell as a Text.
Even VBA does not like displaying such big numbers:
Public Sub TestMe()
Dim inputString As String: inputString = "123456789012345678"
Dim someValue As Double
someValue = inputString
Debug.Print someValue + 1
End Sub
gets: 1,23456789012346E+17
To present the text value in Excel cell, make sure that you format the cell before putting the text in it:
Option Explicit
Public Sub TestMe()
With Range("D2")
.NumberFormat = "#"
.Value2 = "123456789012345678"
End With
End Sub

trying to to get specifically ordered data from .txt and then converting and storing it to double or string arrays at visual basic

I am trying, for several days, to take specifically ordered data from a .txt file and then convert and store it to double or string arrays
the data is stored in the file in this way:
1 0 1 0 >= 15
0 1 0 1 >= 28
1 1 0 0 <= 30
0 0 3 1 <= 22
-1 0 2 0 <= 0
(one line after the other with no blank lines between them)
and my code for this goes like:
Using stream As System.IO.FileStream = System.IO.File.OpenRead("C:\Users\user\Desktop\test_new.txt")
Using reader As New System.IO.StreamReader(stream)
Dim lineCount = File.ReadAllLines("C:\Users\user\Desktop\test_new.txt").Length
Dim line As String = reader.ReadLine()
Dim aryTextFile() As String
Dim operator1() As String
Dim variables(,) As Double
Dim results() As Double
Dim counter3 As Integer
counter3 = 0
NRows = lineCount
While (line IsNot Nothing)
Dim columns = line.Split(" ")
aryTextFile = line.Split(" ")
line = reader.ReadLine()
NVars = columns.Length - 3
For j = 0 To UBound(aryTextFile) - 3
variables(counter3, j) = CDbl(aryTextFile(j))
Next j
For j = NVars To UBound(aryTextFile) - 2
operator1(counter3) = CStr(aryTextFile(j))
Next j
For j = UBound(aryTextFile) - 2 To UBound(aryTextFile) - 1
results(counter3) = CDbl(aryTextFile(j))
Next j
counter3 = counter3 + 1
End While
End Using
End Using
I'm getting warnings which result in errors ofc.
Variable 'variables' is used before it has been assigned a value. A null reference exception could result at
runtime. C:\Users\user\Documents\Visual Studio
2008\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 230 25 WindowsApplication1
Variable 'operator1' is used before it has been assigned a value. A null reference exception could result at
runtime. C:\Users\user\Documents\Visual Studio
2008\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 236 25 WindowsApplication1
Variable 'results' is used before it has been assigned a value. A null reference exception could result at
runtime. C:\Users\user\Documents\Visual Studio
2008\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 243 25 WindowsApplication1
So what am I doing wrong and how can I fix it
note: data is saved from dynamic matrixes, so it can be a lot bigger than the displayed example (several lines with several columns), and that is the reason I'm trying to program it, in order to save me some lab time of copying and pasting it manually...
thanks in advance,
Viktor
p.s. if another member or admin can indicate an older post about my question, that would also be very helpful, but I am reading posts for the last 4 days in similar questions and I couldn't find something working for me
p.s.2 since is my first post, I have also tried to attach the project and I couldn't find a way :)
You need to define the dimensions of your arrays before trying to use them.
If you don't know what the size will be use a list instead.
'No defined size - Warning
Dim array1() As String
'Error when trying to access
array1(4) = "Testing"
'Defined size
Dim array2(10) As String
array2(5) = "Testing"

VBNewLine after certain number of characters AND a given character

All,
I developed a formatting/comma-delimiting application that turns a long string of numbers into the correct format for SQL queries.
For example:
101
102
103
104
105
Becomes:
('101','102','103','104','105')
It's a very useful tool, but lets say there are 500 different values to format. This creates a very long line in SQL server.
I've been searching on the internet, but I have yet to find something that can accomplish my question:
How do I word wrap to 100 characters per line, but not breaking up the format:
('Value1','Value2','Value3')
Please let me know if I need to explain further. Thanks for the help!
This will convert the "long string of numbers" into sql format with a lineLength parameter:
Public Function ConvertToSqlParameter(input As String, lineLength As Integer) As String
Dim sb = New StringBuilder("(")
Dim len = 0
For Each s In input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
If len >= lineLength Then
sb.Append(Environment.NewLine)
len = 0
End If
Dim str = "'" + s + "',"
len += str.Length
sb.Append(str)
Next
sb.Length -= 1
sb.Append(")")
Return sb.ToString()
End Function