VB - Caesar Cipher emulation - vb.net

I'm trying to emulate Caesar Cipher encryption. The problem is whenever I input "wxyz"
(shifted by 3) the output is "z{|}". But the expected output should be "zabc".
Anyone knows what to add?
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim plaintext As String = TextBox1.Text
Dim charArray() As Char = plaintext.ToCharArray
Dim shift = TextBox2.Text
Dim character As String
Dim temp As String
TextBox3.Text = ""
If shift <> "" And IsNumeric(shift) Then
If plaintext = "" Then
MsgBox("Please input some plain text")
Exit Sub
End If
If shift > 26 Then
MsgBox("Maximum shifts reached. Limit is 26!!")
Exit Sub
End If
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
TextBox3.Text += character
Next
Exit Sub
Else
MsgBox("Input numbers only!!")
End If
End Sub

When you shift an Ascii code you should verify that it does not get greater than 122, which is the Ascii code for the character "z". If you go beyond that point, you will get punctuation marks, symbols and that stuff. Google "ASCII table" and you can easily see it for yourself.
So, to solve your problem, if the Ascii code you get after shifting is greater than 122 you should go back and begin by 97 again, which is the ascii for "a".
So, instead of this:
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
TextBox3.Text += character
Next
You should do something like
For loope = 0 To charArray.Length - 1 Step +1
temp = charArray(loope)
character = Chr(Asc(temp) + shift)
' You substract 26, the whole length of the alphabet
If character > 122 Then
character = character - 26
End If
TextBox3.Text += character
Next
No quite sure that this would be stable if shift is greater than 26, but anyhow you already check its value so it should work.

Related

Is it possible to convert vba code that can be used in vbnet?

Good day,
I have this code that I used from vba excel
Private Sub txtSTime_Change()
Dim ascii As Integer
Dim h As Integer
Dim m As Integer
Dim n As Integer
n = Len(txtSTime.Value)
If n = 0 Then Exit Sub
ascii = Asc(Right(txtSTime.Value, 1))
' Validate the hour is 2 digits from 01 to 23.
If n = 2 And ascii <> 58 And CharCode <> 8 Then
h = CInt(Left(txtSTime.Value, 2))
If h < 0 Or h > 23 Then
MsgBox "Invalid hour " & h & vbLf & "Hours are from 00 to 23."
txtSTime.Value = ""
Me.txtSTime.SetFocus
Exit Sub
End If
End If
' Validate the month is 2 digits from 01 to 12.
If n = 5 And ascii <> 58 And CharCode <> 8 Then
m = CInt(Mid(txtSTime.Value, 4, 2))
If m < 0 Or m > 59 Then
MsgBox "Invalid minute " & m & vbLf & "Minutes are from 00 to 59."
txtSTime.Value = Left(txtSTime.Value, 3)
Me.txtSTime.SetFocus
txtSTime.Value = ""
End If
End If
End Sub
Private Sub txtSTime_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
CharCode = 0
n = KeyCode
Select Case KeyCode
Case 8, 10, 13, 46: CharCode = KeyCode ' Process these control characters: BS, LF, CR and Delete.
Case 48 To 57, 96 To 105 ' Display numbers and forward slahes from keyboard and number pad.
Case 186 And Shift = 1 ' Display the colon.
Case Else: KeyCode = 0 ' Erase all other input.
End Select
End Sub
Private Sub txtSTime_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim char As String
Dim n As Integer
n = Len(txtSTime)
If n > 0 Then char = Right(txtSTime, 1)
Select Case KeyCode
Case 48 To 57, 96 To 105
' Automatically add the colon after the day and month.
If n = 3 Then
txtSTime.Value = Left(txtSTime.Value, n - 1) & ":" & char
End If
Case 183 And Shift = 1
' Display the colon only after the minutes.
If n <> 3 Then
txtSTime.Value = Left(txtSTime.Value, n - 1)
End If
End Select
End Sub
Its function is that whenever I type number on my txtSTime textbox it automatically change the number into an 24Hour time format.
Example I typed "1220" it automatically change into "12:20"
I tried looking for the same function in vb.net but I can't seem to find anything.
It is possible to convert the code from vba excel that can be used in vb.net?
I was from VBA as well and now I'm practicing VB.net and C#
It does not have to be that complicated now days. As for your solution, there are 2 things you need to take care. First make the user is entering numeric. You may refer to
VB.net Need Text Box to Only Accept Numbers
Secondly, you can use a split function to format your text
Dim txt As String = txtSTime.Text
Dim Result As String = txt.Substring(0, 2) & ":" & txt.Substring(3, 2)
txtSTime.Text = Result

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

vb.net Line numbering in multi line Rich Text Box if line starts with specific condition

Let me start by saying that I'm new to any language of coding besides G-code, and I've researched this until my fingers hurt. I've actually been working on this project for a little over a year now on my own, and this is the first hurdle I haven't been able to find my way around.
I'm creating an editor for cnc G-code, and i'm trying to add a Re-number function to it. I'm using a multi line richtextbox to display the the G-code to the user. I'm trying to edit each line of code that starts with the character "N", and if a line doesn't start with that character then it's left alone.
I figured the best way to do this would be to loop thru the RTB and pass each line into an array. Then I could use an If statement to see if a cell in the array started with the char "N" or in my case "blockLetter". Then use the replace function to correct the line Number.
This is what I have so far.
Dim increment As Integer = txtLNIncrement.Text
Dim blockLetter As String = txtLNStartTxt.Text
Dim count As Integer = 0
Dim block As Integer = count + increment
For Each cell As String In frmNC.NcTextBox.Lines
If cell.StartsWith(blockLetter) Then
Dim newCell As String = cell.Replace(blockLetter, block)
block = block + increment
MessageBox.Show(newCell)
End If
Next
Example of G-code that needs to be renumbered:
N50 M01
N60 T0101 (TOOL NAME)
N70 M41
N80 G96 S350
N90 M03
N100 M08
This is what I want:
N10 M01
N20 T0101 (TOOL NAME)
N30 M41
N40 G96 S350
N50 M03
N60 M08
This is what I'm getting when I run the code above:
1050 M01
2060 T0101 (TOOL NAME)
3070 M41
4080 G96 S350
5090 M03
60100 M08
I believe my issue is that the cell.replace is splitting each cell at the "N" character, and dropping it all together. Thus adding what I want to see in front of the existing numbers, minus the "N" character. How can I overwrite the existing block number to the correct ascending block number, and retain the "N" character? Am I going about this in the correct way, or is there a better way? Any help is greatly appreciated.
Try something like this out:
Private increment As Integer = 10
Private blockLetter As String = "N"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim newLine As String
Dim values() As String
Dim lineNumber As Integer = 0
Dim lines As New List(Of String)(NcTextBox.Lines)
For i As Integer = 0 To lines.Count - 1
If lines(i).TrimStart().StartsWith(blockLetter) Then
values = lines(i).TrimStart(" " & blockLetter.ToCharArray).Split(" ")
lineNumber = lineNumber + increment
values(0) = lineNumber
newLine = blockLetter & String.Join(" ", values)
lines(i) = newLine
End If
Next
NcTextBox.Lines = lines.ToArray
End Sub
it's very simple:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim blockLetter As String = "N"
Dim increment As Integer = 1
For i As Integer = 0 To RichTextBox1.Lines.Length - 1 Step 1
Dim fullLine As String = RichTextBox1.Lines(i)
If fullLine.StartsWith(blockLetter) Then
Dim numbering As String = fullLine.Remove(RichTextBox1.Lines(i).IndexOf(" "))
Dim block As Integer = numbering.Substring(1)
Dim newCell As String = blockLetter & block + increment
MessageBox.Show(newCell)
End If
Next
End Sub
Result:
The Label1.Text will increase with button click.
It's all about Substring() starting from index 1 after 'N', so you will get the number.
Good luck with your coding!

Detect the sign in number input

how can i detect if the input number in textbox contains "-"
so i can change the output into positive number and
if not contain "-" the output number is become negative
i'm using Vb.net 2010 tnx in advance for who wants to help
Dim output As String
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If getbyte(TextBox1.Text, 0) = Chr(45) Then ' check whether the first character is - or not
output = New String((From c As Char In TextBox1.Text Select c Where Char.IsDigit(c)).ToArray())
else
output="-" & textbox1.text
End If
msgbox (CInt(output))' will give the number
End Sub
Getbyte function to take each character from a string based on the position
Private Function getbyte(ByVal s As String, ByVal place As Integer) As String
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function
if you want to convert the -eve number to positive for calculation you can use
You have couple of options, two of them are:
1) Use StartsWith functions:
If Textbox1.Text.Trim().StartsWith("-"))Then
' It is a negative number
End If
2) If you just need to toggle the number sign, then:
Dim number as Integer = Integer.Parse(Textbox1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Using option2, i get:
Dim txta1 As New TextBox
txta1.Text = "-2"
Dim number As Double = Double.Parse(txta1.Text) ' Preferrably use Integer.TryParse()
number *= -1 ' Toggle the number sign
Dim s As String = number & " | "
Output: 2 |