Adding digits depending on the length of a String - vb.net

I want a code in vb.net with something like the following, my problem is at the last statement where I'm failing to create a 16 digits string from the missing digits which is equal to C.
Dim A as string
Dim B as a string
Dim C as integer
if len(A) = 16 then
B = A
elseif Len(A) > 16 then
B = first 16 digits of A, 'ignore the rest if the digits'
elseif len(A) < 16 then
C = 16 - len(A)
B = A & digits equal to count of C 'Making Len(B) = 16'
else
end if

I have used the .net String class which is part of the .net Framework in the System namespace.
String.Length is a property of a String. It replaces the old VB6 Len method.
String.Substring has several overloads. The one I used here has 2 integers as arguments. The first one is the starting index and the second one is the length of the string to be returned.
String.PadRight has two arguments. The first is an Integer providing the total lenght of the new string. The second is a Char provided the character to pad with. The little c following differentiates a String from a Char literal for the compiler.
You can see all the String methods and properties at https://learn.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.8
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim PaddedString As String = Get16String(TextBox1.Text)
Debug.Print(PaddedString)
End Sub
Private Function Get16String(Input As String) As String
Dim B As String = ""
If Input.Length = 16 Then
B = Input
ElseIf Input.Length > 16 Then
B = Input.Substring(0, 16)
ElseIf Input.Length < 16 Then
B = Input.PadRight(16, "0"c)
End If
Return B
End Function

Related

The code gives leading zeros in hex to binary output

The code gives additional 4 zeros, where the output should be without leading zeros. But I can't just trim it because with a different hex output it seems to produce different results. where did that four zeros come from? optionstrict on
The wrong output from the code (notice the additional leading 0000 in the wrong output in the front)
0000101001110011101011000110110111000000100000010010000001100000111111101101111101001010111110101011101001001100100101110111010011010110101101101100110000110110110000111001100100000111010011001011110110110010111111110000101011110010111010001000010100000101
The correct and expected binary should be (converted with an online hex to binary tool)
101001110011101011000110110111000000100000010010000001100000111111101101111101001010111110101011101001001100100101110111010011010110101101101100110000110110110000111001100100000111010011001011110110110010111111110000101011110010111010001000010100000101
The VB.net code I used
Private Function HexStringToByteArray(ByVal shex As String) As Byte()
Dim B As Byte() = Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
Return Enumerable.Range(0, shex.Length).Where(Function(x) x Mod 2 = 0).[Select](Function(x) Convert.ToByte(shex.Substring(x, 2), 16)).ToArray()
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim hex As String = "0a73ac6dc0812060fedf4afaba4c9774d6b6cc36c399074cbdb2ff0af2e88505"
Dim bytes As Byte() = HexStringToByteArray(hex)
If BitConverter.IsLittleEndian Then
Array.Reverse(bytes)
End If
Dim myBA3 As New BitArray(bytes)
Dim myba3_reversed As New BitArray(myBA3.Length)
Dim count As Integer = (myBA3.Count - 1)
Dim myba3BITS As String = Nothing
For i = 0 To myBA3.Count - 1
If myBA3(i) = True Then
myba3BITS &= "1"
End If
If myBA3(i) = False Then
myba3BITS &= "0"
End If
count = (myBA3.Count - 1) - i
myba3_reversed(i) = myBA3(count)
Next i
Dim reversedBITS As String = Nothing
For i = 0 To myba3_reversed.Count - 1
If myba3_reversed(i) = True Then
reversedBITS &= "1"
End If
If myba3_reversed(i) = False Then
reversedBITS &= "0"
End If
Next i
Dim bits As String = reversedBITS
End Sub
Your input starts with "0a". If I use the Windows Calculator app in Programmer mode and enter that in HEX, the BIN output is "1010". Your code is taking each pair of hexadecimal digits and outputting eight binary digits, a buye for a byte. If you wanted to express the binary value 1010 in eight digits, what would it look like? You'd pad the value with four leading zeroes, wouldn't you? Where have you see that before? If your input doesn't have aleading zero then you need to add one. If your output does have leading zeroes and you don't want them, take them off. This is why you need to actually understand what your code is doing.

Splitting string every 100 characters not working

I am having a problem where I just can't seem to get it to split or even display the message. The message variable is predefined in another part of my code and I have debugged to make sure that the value comes through. I am trying to get it so that every 100 characters it goes onto a new line and with every message it also goes onto a new line.
y = y - 13
messagearray.AddRange(Message.Split(ChrW(100)))
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0
Label1.Text = Label1.Text & vbCrLf & messagefin
Label1.Location = New Point(5, 398 + y)
You can use regular expression. It will create the array of strings where every string contains 100 characters. If the amount of remained characters is less than 100, it will match all of them.
Dim input = New String("A", 310)
Dim mc = Regex.Matches(input, ".{1,100}")
For Each m As Match In mc
'// Do something
MsgBox(m.Value)
Next
You can use LINQ to do that.
When you do a Select you can get the index of the item by including a second parameter. Then group the characters by that index divided by the line length so, the first character has index 0, and 0 \ 100 = 0, all the way up to the hundredth char which has index 99: 99 \ 100 = 0. The next hundred chars have 100 \ 100 = 1 to 199 \ 100 = 1, and so on (\ is the integer division operator in VB.NET).
Dim message = New String("A"c, 100)
message &= New String("B"c, 100)
message &= New String("C"c, 99)
Dim lineLength = 100
Dim q = message.Select(Function(c, i) New With {.Char = c, .Idx = i}).
GroupBy(Function(a) a.Idx \ lineLength).
Select(Function(b) String.Join("", b.Select(Function(d) d.Char)))
TextBox1.AppendText(vbCrLf & String.Join(vbCrLf, q))
It is easy to see how to change the line length because it is in a variable with a meaningful name, for example I set it to 50 to get the output
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
You can use String.SubString to do that. Like this
Dim Message As String = "your message here"
Dim MessageList As New List (Of String)
For i As Integer = 0 To Message.Length Step 100
If (Message.Length < i + 100) Then
MessageList.Add(Message.SubString (i, Message.Length - i)
Exit For
Else
MessageList.Add(Message.SubString (i, 100))
End If
Next
Dim k = MessageList.Count - 1
...
Here is what your code produced with a bit of clean up. I ignored the new position of the label.
Private Sub OpCode()
Dim messagearray As New List(Of String) 'I guessed that messagearray was a List(Of T)
messagearray.AddRange(Message.Split(ChrW(100))) 'ChrW(100) is lowercase d
Dim k = messagearray.Count - 1
Dim messagefin As String
messagefin = ""
While k > -1
messagefin = messagefin + vbCrLf + messagearray(k)
k = k - 1
End While
k = 0 'Why reset k? It falls out of scope at End Sub
Label1.Text = Label1.Text & vbCrLf & messagefin
End Sub
I am not sure why you think that splitting a string by lowercase d would have anything to do with getting 100 characters. As you can see the code reversed the order of the list items. It also added a blank line between the existing text in the label (In this case Label1) and the new text.
To accomplish your goal, I first created a List(Of String) to store the chunks. The For loop starts at the beginning of the input string and keeps going to the end increasing by 10 on each iteration.
To avoid an index out of range which would happen at the end. Say, we only had 6 characters left from start index. If we tried to retrieve 10 characters we would have an index out of range.
At the end we join the elements of the string with the separated of new line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BreakInto10CharacterChunks("The quick brown fox jumped over the lazy dogs.")
End Sub
Private Sub BreakInto10CharacterChunks(input As String)
Dim output As New List(Of String)
Dim chunk As String
For StartIndex = 0 To input.Length Step 10
If StartIndex + 10 > input.Length Then
chunk = input.Substring(StartIndex, input.Length - StartIndex)
Else
chunk = input.Substring(StartIndex, 10)
End If
output.Add(chunk)
Next
Label1.Text &= vbCrLf & String.Join(vbCrLf, output)
End Sub
Be sure to look up String.SubString and String.Join to fully understand how these methods work.
https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.8
and https://learn.microsoft.com/en-us/dotnet/api/system.string.join?view=netframework-4.8

Reversing Digits

I'm trying to make a function that takes a three digit number and reverses it (543 into 345)
I can't take that value from a TextBox because I need it to use the three numbers trick to find a value.
RVal = ReverseDigits(Val)
Diff = Val - RVal
RDiff = ReverseDigits(Diff)
OVal = Diff + RDiff
543-345=198
198+891=1089
Then it puts 1089 in a TextBox
Function ReverseDigits(ByVal Value As Integer) As Integer
' Take input as abc
' Output is (c * 100 + b * 10 + a) = cba
Dim ReturnValue As Boolean = True
Dim Val As String = CStr(InputTextBox.Text)
Dim a As Char = Val(0)
Dim b As Char = Val(1)
Dim c As Char = Val(2)
Value = (c * 100) + (b * 10) + (a)
Return ReturnValue
End Function
I've tried this but can't figure out why it won't work.
You can convert the integer to a string, reverse the string, then convert back to an integer. You may want to enforce the three digit requirement. You can validate the argument before attempting conversion
Public Function ReverseDigits(value As Integer) As Integer
If Not (value > 99 AndAlso value < 1000) Then Throw New ArgumentException("value")
Return Integer.Parse(New String(value.ToString().Reverse().ToArray()))
End Function
My code is pretty simple and will also work for numbers that don't have three digits assuming you remove that validation. To see what's wrong with your code, there are a couple of things. See the commented lines which I changed. The main issue is using Val as a variable name, then trying to index the string like Val(0). Val is a built in function to vb.net and the compiler may interpret Val(0) as a function instead of indexing a string.
Function ReverseDigits(ByVal Value As Integer) As Integer
' Dim ReturnValue As Boolean = True
' Dim Val As String = CStr(InputTextBox.Text)
Dim s As String = CStr(Value)
Dim a As Char = s(0)
Dim b As Char = s(1)
Dim c As Char = s(2)
Value = Val(c) * 100 + Val(b) * 10 + Val(a)
'Return ReturnValue
Return Value
End Function
(Or the reduced version of your function, but I would still not hard-code the indices because it's limiting your function from expanding to more or less than 3 digits)
Public Function ReverseDigits(Value As Integer) As Integer
Dim s = CStr(Value)
Return 100 * Val(s(2)) + 10 * Val(s(1)) + Val(s(0))
End Function
And you could call the function like this
Dim inputString = InputTextBox.Text
Dim inputNumber = Integer.Parse(inputString)
Dim reversedNumber = ReverseDigits(inputNumber)
Bonus: If you really want to use use math to find the reversed number, here is a version which works for any number of digits
Public Function ReverseDigits(value As Integer) As Integer
Dim s = CStr(value)
Dim result As Integer
For i = 0 To Len(s) - 1
result += CInt(Val(s(i)) * (10 ^ i))
Next
Return result
End Function
Here's a method I wrote recently when someone else posted basically the same question elsewhere, probably doing the same homework:
Private Function ReverseNumber(input As Integer) As Integer
Dim output = 0
Do Until input = 0
output = output * 10 + input Mod 10
input = input \ 10
Loop
Return output
End Function
That will work on a number of any length.

Random generate numbers and letters based on 2 symbols as letters and numbers and using a -

This is a number #
This is a number or letter?
Separate the random string like ??#?#-???##-#?#???-#???#-##
I need some code that generates the string as shown above. It doesn't have to be complicated.
Expected result example: 2F421-QD421-2W3FY0-3F4L1-37
I've tried using PHP and this example but wasn't able to achieve what I was looking for Generating a random numbers and letters
I am looking for a vb.net project to handle the generation so i can submit the serial into a database manually.
I quite like this approach:
Dim characters = "0123456789ABCDEFGHIJKLOMNOPQRSTUVWXYZ"
Dim template = "??#?#-???##-#?#???-#???#-##"
Dim rnd = New Random()
Dim query =
From t In template
Select If(t = "-", "-", characters(rnd.Next(If(t = "?", characters.Length, 10))))
Dim result = String.Join("", query)
Console.WriteLine(result)
It gives me output like this:
RC2C9-DHB47-1Q07RL-8BIF7-57
Create 2 functions 1 for letters GRL (Generate Random Letter) 1 for numbers GRN (Generate Random Number) like so:
Result of what i called is: W96-GKlF6
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Console.WriteLine(GRL(1) + GRN(2) + "-" + GRL(4) + GRN(1))
End Sub
Public Function GRL(ByRef iLength As Integer) As String
Static rdm As New Random()
Dim allowChrs() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ".ToCharArray()
Dim sResult As String = String.Empty
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End Function
Public Function GRN(ByRef iLength As Integer) As String
Static rdm As New Random()
Dim allowChrs() As Char = "0123456789".ToCharArray()
Dim sResult As String = String.Empty
For i As Integer = 0 To iLength - 1
sResult += allowChrs(rdm.Next(0, allowChrs.Length))
Next
Return sResult
End Function
Easy, random numbers to use as ASCII codes, then check the position to delimit if its going to be just a number or a character that can be number or letter.
When is a position that can be number or letter, analyze the random number and split it. If the number is less than 11 that means is a number then add 47 and use the result as ASCII code (random create numbers from 1 to 36) so for example if the random is 1, we say 47 + 1 = 48, 48 is the ASCII code of 0.
If the number is 11 or more we add 54, so for example if random is 11 then we have 11 + 54 = 65. 65 is the ASCII code for the letter A.
Dim Key As String = ""
Dim N As Integer
Randomize()
For t = 1 To 23
If t = 3 Or t = 5 Or t = 9 Or t = 10 Or t = 11 Or t = 13 Or t = 17 Or t >= 21 Then
N = 10
Else
N = 36
End If
Dim value As Integer = CInt(Int(N * Rnd() + 1))
If value < 11 Then
Key = Key & Chr(value + 47)
Else
Key = Key & Chr(value + 54)
End If
If t = 5 Or t = 10 Or t = 16 Or t = 21 Then
Key = Key & "-"
End If
Next

Check String for identical Digits

I'm asking my users to enter a 4 - 6 digit numberic PIN. And I'd like to make sure users can't enter 0000 or 11111 or 333333. How can I check a string for 4 consecutive identical digits? I'm using vb.net.
See code snippet below:
Sub Main()
Dim a As String = "001111"
Dim b As String = "1123134"
Dim c As String = "1111"
Console.WriteLine(CheckConsecutiveChars(a, 4)) 'True => Invalid Pin
Console.WriteLine(CheckConsecutiveChars(b, 4)) 'False => Valid Pin
Console.WriteLine(CheckConsecutiveChars(c, 4)) 'True => Invalid Pin
Console.ReadLine()
End Sub
'maxnumber = maximum number of identical consecutive characters in a string
Public Function CheckConsecutiveChars(ByVal j As String, ByVal maxNumber As Integer) As Boolean
Dim index As Integer = 0
While ((index + maxNumber) <= j.Length)
If (j.Substring(index, maxNumber).Distinct.Count = 1) Then
Return True
End If
index = index + 1
End While
Return False
End Function
The method String.Distinct.Count() counts the number of distinct characters in a string. You cast your digit to a String and test for the number of different characters. If the result is 1 then the user has entered the same number.
Note: If you're using the Substring, you must check the length of the string first (is it long enough) to avoid exceptions.
This answer is similar to the accepted answer, but does not create lots of temporary strings in memory.
'maxnumber = maximum number of identical consecutive characters in a string
Public Function HasConsecutiveChars(ByVal j As String, ByVal maxNumber As Integer) As Boolean
Dim result As Boolean = False
Dim consecutiveChars As Integer = 1
Dim prevChar As Char = "x"c
For Each c in j
If c = prevChar Then
consecutiveChars += 1
If consecutiveChars >= maxNumber Then
result = True
Exit For
End If
Else
consecutiveChars = 1
End If
prevChar = c
Next
Return result
End Function