VB.net detect if a number is decimal or hexadecimal - vb.net

I have a VB.NET application and I need to check if the number entered in a string is in it's hexadecimal or decimal format
For example, look here:
1559727743788
0000016B2704A32C
This is the same number written in decimal format (first) and hex format (second).
How can I write a function that auto-detects the case? Thanks

As Steve points out, a string that consists only of decimal digits can be either a decimal number or a hexadecimal number. Here is some code that will test the contents of TextBox and report (a) if it could be a decimal number and also (b) if it could be a hex number. The code assumes that hex numbers always have an even number of digits. If that is not desired, remove the (num.Length Mod 2 = 0) AndAlso
Dim decNum, hexNum As Boolean
Dim num As String = TextBox1.Text
If num <> "" Then
decNum = num.All(Function(c) Char.IsDigit(c))
hexNum = (num.Length Mod 2 = 0) AndAlso num.All(Function(c) "0123456789abcdefABCDEF".Contains(c))
End If
Label1.Text = "Possible dec: " & decNum & " - possible hex: " & hexNum

Related

increment alphanumeric string where alphabet position in a string is keeps changing

I need to save Multiple(about 20-25) serial number of the specimen in my application. Sometimes serial number will be alphanumeric but will be sequential. I need a way out to increment alphanumeric serial numbers based on the first serial number entered.
My main problem is alphabet position and alphabet count keeps changing. Example : 10MG2015 20562MG0 MGX02526 etc etc
I tried but mine works when Alphabet are in starting position and when there are known number of alphabets. Here is my try
Dim intValue as integer
Dim serialno as string
Dim serialno1 as string
For i =0 to 20
Serialno1 = serialno.Substring(3)
Int32.TryParse(Serialno1, intValue)
intValue = intValue + 1
checkedox1.items.add(serialno.Substring(0,3) + intValue.ToString("D3"))
NEXT
Any help is highly appreciated. Thanks in advance
edit 1
Clarity : I want to increment alphanumeric string. Example : If first entered one is 10MG2015 then I should increment to 10MG2016, 10MG2017, 10MG2018, 10MG2019 and so on... For 20562MG0 it will be 20562MG1, 20562MG2 20562MG3 and so on...
Function FindSequenceNumber(SerialNumber As String) As Integer
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim result As Integer = -1
Dim m As Match = sequenceExpr.Match(SerialNumber)
If m.Success AndAlso Integer.TryParse(m.Groups(1).Value, result) Then
Return result
Else
'Throw exception, return -1, etc
End If
End Function
See it here:
https://dotnetfiddle.net/gO2nue
Note: the integer type doesn't preserve leading zeros. You may find it better to return a tuple with either the length of the original string, so you can pad zeros to the left if needed to match the original formatting.
Or maybe this:
Function IncrementSerial(SerialNumber As String) As String
'Look for at least four digits in a row, and capture all the digits
Dim sequenceExpr As New Regex("([0-9]{4,11})")
Dim m As Match = sequenceExpr.Match(SerialNumber)
If Not m.Success Then Throw New Exception("No sequence number found")
Dim c = m.Groups(1).Captures(0)
Dim seq = (Integer.Parse(c.Value) + 1).ToString()
If seq.Length < c.Value.Length Then
seq = seq.PadLeft(c.Value.Length, "0"c)
End If
Dim result As String = ""
If c.Index > 0 Then result & = SerialNumber.Substring(0, c.Index)
result &= seq
If c.Index + seq.Length < SerialNumber.Length Then result &= SerialNumber.SubString(c.Index + seq.Length)
Return result
End Function

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

How does the Val() function in VB.NET work?

I have an assignment in VB.NET that I'm stuck with at the moment. Would love some help.
The question is this: You enter random characters into a textbox, for example 12ab3c4d5efgh, and at the click of a button, it must sort the characters in the textbox into 2 separate Labels, depending on whether or not the 'character' is a number or letter. So, continuing the example, Label1 must show '12345' and Label 2 must show 'abcdefgh'. I hope I made myself clear enough.
I was asked to use the Val() function but I really have no clue. Could someone please help? :D
This creates one string with the digits and one with the letters. Characters that are not digits or letters are ignored.
Dim chars As String = "12ab3c4d5efgh"
Dim nums As String = chars.Where(Function(c) Char.IsDigit(c)).ToArray
Dim lets As String = chars.Where(Function(c) Char.IsLetter(c)).ToArray
If you have to use Val() something like this would do. But be careful: Val("0") also returns 0.
Dim numbers As String = String.Empty
Dim letters As String = String.Empty
Dim sourceString As String = "12ab3c4d50efgh"
For Each c As Char In sourceString
If Val(c) = 0 And c <> "0" Then letters &= c Else numbers &= c
Next
Console.WriteLine("Numbers: " & numbers)
Console.WriteLine("Letters: " & letters)
Console.ReadKey()

How to find a letter in between two letters in visual basic?

Sorry for the awkwardly worded question. In visual basic I have a prompt asking the user to "Enter a letter between A and D:"
If ValidChar(chrLetter) Then
Me.lblLetterResult.Text = chrLetter & " is a valid letter"
Else
Me.lblLetterResult.Text = chrLetter & " is not a valid letter"
End If
Function ValidChar(ByVal chrLetter As Char) As Boolean
Dim chrLowChar As Char = "D"
Dim chrHighChar As Char = "A"
If chrLetter >= chrLowChar And chrLetter <= chrHighChar Then
Return True
Else
Return False
End If
End Function
Obviously this isn't correct, but I'm not sure what the correct code should be. If the user were to enter the character "A" then it should display "A is a valid number". If the user were to enter "X" then it should display "X is not a valid number". Any help is appreciated!
Don't you just need to reverse your logic? D is greater than A.
Dim chrLowChar As Char = "A" ' ascii decimal value of 65
Dim chrHighChar As Char = "D" ' ascii decimal value of 68
Review decimal values for ASCII characters for more information on character values
http://www.asciitable.com/
Just create a string object "ABCD". Execute string.contains(). If using a wider range just convert to ASCII equivalent and use code similar to your example

Variable truncates when using messagebox

I have a strange problem here. In my code, variable b string, has the value "Test Test Test". This value we can see while debugging the variable as well as in the text visualizer.
Now the problem is, if I show the same string using Messagebox, the value is just "Test". What can I do here to get the complete value.
I am converting from an ebcdic encoded bytes to corresponding utf8 string and doing the above operation. Any thoughts. below is my sample code.
Dim hex As String = "e385a2a300000000e385a2a3000000e385a2a3"
Dim raw As Byte() = New Byte((hex.Length / 2) - 1) {}
Dim i As Integer
For i = 0 To raw.Length - 1
raw(i) = Convert.ToByte(hex.Substring((i * 2), 2), &H10)
Next i
Dim w As String = System.Text.Encoding.GetEncoding(37).GetString(raw)
Dim raw1 As Byte() = Encoding.UTF8.GetBytes(w)
Dim b As String = Encoding.UTF8.GetString(raw1)
MessageBox.Show(b)
Look at the byte array. You have 4 ASCII 0's after each "Test". ASCII character code 0 corresponds to nul, which is a string termination sequence. If you want spaces instead of nulls there...
Dim b As String = Encoding.UTF8.GetString(raw1).Replace(Chr(0), " ")
It is possible that the string "b" might contains some control character.
To test a control char in string.
For Each p As Char In b
MsgBox(p & " " & Char.IsControl(p) & " " & AscW(p))
Next
Use String#Replace to replace control chars.
b = b.Replace(ChrW(0), " ")
MsgBox(b)