Andrea
Andrea

Reputation: 37

VB.net detect if a number is decimal or hexadecimal

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

Upvotes: 1

Views: 1367

Answers (1)

Blackwood
Blackwood

Reputation: 4534

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

Upvotes: 2

Related Questions