I am writing the vb.net to right padding the values. my code as follows:
Dim Ni As Byte() = { &HA6, &H02, &H01,....}
Dim Nca As Byte() = { &H12, &H00, &H02,....}
If (Ni.Length <= Nca.Length - 36) Then
Dim padLength As Integer = Nca.Length - 36 - Ni.Length
Dim padvalue As Byte() = {&HBB}
For Each w As Integer In padLength
Console.Write(Ni =Ni+ Ni.rigtPadding({&HBB}))
Next
End If
my code is not working. If Ni.Length<=Nca.Length-36, I need consist of the full Ni padded to the right with Nca-36-Ni bytes of hex value "&HBB". it is might be more than 1 "&HBB" need to be padded on the right side. and then I need the final result of Ni with the padding.
Ni is Issuer public key, Nca is CA public key ,the final result I want should be {&H6A, 02, 11, FF,....., BB,BB,BB}
Thank you very much for any help and comment.
Since you're using regular arrays this is relatively simple (but could be even simpler using a List(Of T)).
First you need to call Array.Resize() in order to increase the size of the array. Then you can use a regular For loop to fill the new space.
Dim prevLength As Integer = Ni.Length 'Store the previous length so we can start looping from it.
Array.Resize(Ni, Ni.Length + padLength) 'Take the original length and increase it by how much needs to be padded.
'Iterate from the beginning of the padding to the new end of the array.
For i = prevLength To Ni.Length - 1
Ni(i) = &HBB
Next
I also suggest you read up a little on how arrays work: Arrays in Visual Basic - Microsoft Docs.
You can manually resize NCI using Redim Preserve and set the padding character:
Dim Padding as Byte = &HBB
Dim Nca As Byte() = { &H12, &H00, &H02,....}
Dim Ni As Byte() = { &HA6, &H02, &H01,....}
Dim len = Nca.Length - 36
if (len > Ni.Length) Then
Redim Preserve Ni(len+1)
For i As Integer = len to Ni.Length-1
Ni(i) = Padding
Next
End if
Or you can use LINQ:
Dim Padding as Byte = &HBB
Dim Pad =Function(i) If(i < Nca.Length, Nca(i), padding)
Dim Nca As Byte() = { &H12, &H00, &H02,....}
Dim len as integer = Nca.Length - 36
if len > Ni.Length Then Ni = Enumerable.Range(0, len+1).Select(Pad).ToArray()
Related
I'm using Logo right now and i'm making a project and basically i want to turn your recorded voice into something visual, only problem is when i go to find code it re that works it requires 1: A picture box and 2: to manually grab the sound .wav file and place it. I already made code to record my voice and to make it into a .Wav file and i already have code to visualize it, just when i run it it appears as a thick square of lines rather than the example i shown. Note: I'm not drawing into a picturebox, i'm drawing directly into the Form by using g.drawline(bleh,bleh,bleh,bleh).
(Example: http://static1.1.sqspcdn.com/static/f/335152/16812948/1330286658510/76_dsc3616.jpeg?token=R1zPNnr9PAoB3WvnDxfFFFvzkMw%3D )
The code im trying to run:
Public Sub DrawSound(x As Integer, y As Integer)
Dim samplez As New List(Of Short)
Dim maxamount As Short
Dim pic As New Bitmap(x, y)
Dim ratio As Integer = (samplez.Count - 1) / (y - 1) 'If there are 10000 samples and 200 pixels, this would be every 50th sample is shown
Dim halfpic As Integer = (x / 2) 'Simply half the height of the picturebox
GC.Collect()
Dim wavefile() As Byte = IO.File.ReadAllBytes("C:\Users\" & Environ$("Username") & "\Documents\Sounds\Mic.wav")
GC.Collect()
Dim memstream As New IO.MemoryStream(wavefile)
Dim binreader As New IO.BinaryReader(memstream)
Dim ChunkID As Integer = binreader.ReadInt32()
Dim filesize As Integer = binreader.ReadInt32()
Dim rifftype As Integer = binreader.ReadInt32()
Dim fmtID As Integer = binreader.ReadInt32()
Dim fmtsize As Integer = binreader.ReadInt32()
Dim fmtcode As Integer = binreader.ReadInt16()
Dim channels As Integer = binreader.ReadInt16()
Dim samplerate As Integer = binreader.ReadInt32()
Dim fmtAvgBPS As Integer = binreader.ReadInt32()
Dim fmtblockalign As Integer = binreader.ReadInt16()
Dim bitdepth As Integer = binreader.ReadInt16()
If fmtsize = 18 Then
Dim fmtextrasize As Integer = binreader.ReadInt16()
binreader.ReadBytes(fmtextrasize)
End If
Dim DataID As Integer = binreader.ReadInt32()
Dim DataSize As Integer = binreader.ReadInt32()
samplez.Clear()
For i = 0 To (DataSize - 3) / 2
samplez.Add(binreader.ReadInt16())
If samplez(samplez.Count - 1) > maxamount Then 'Using this for the pic
maxamount = samplez(samplez.Count - 1)
End If
Next
For i = 1 To x - 10 Step 2 'Steping 2 because in one go, we do 2 samples
Dim leftdata As Integer = Math.Abs(samplez(i * ratio)) 'Grabbing that N-th sample to display. Using Absolute to show them one direction
Dim leftpercent As Single = leftdata / (maxamount * 2) 'This breaks it down to something like 0.0 to 1.0. Multiplying by 2 to make it half.
Dim leftpicheight As Integer = leftpercent * x 'So when the percent is tied to the height, its only a percent of the height
g.DrawLine(Pens.LimeGreen, i, halfpic, i, leftpicheight + halfpic) 'Draw dat! The half pic puts it in the center
Dim rightdata As Integer = Math.Abs(samplez((i + 1) * ratio)) 'Same thing except we're grabbing i + 1 because we'd skip it because of the 'step 2' on the for statement
Dim rightpercent As Single = -rightdata / (maxamount * 2) 'put a negative infront of data so it goes down.
Dim rightpicheight As Integer = rightpercent * x
g.DrawLine(Pens.Blue, i, halfpic, i, rightpicheight + halfpic)
Next
End Sub
X and Y is the middle of the form. And i also would link where i got the code but i forgot where and also, i modified it in attempt to run it directly into he form rather than a picturebox. It worked sorta haha (And there is so many unused dims but all i know is, once i remove one none of the code works haha) So could anyone help?
I'm trying to figure out how to read a section of bytes (Say 16) starting at a specific address, say 0x2050. I'd like to get the 16 bits output in hex values into a label.
I've been trying to figure out BinaryReader, and FileStreams but I'm not entirely sure what the difference is, or which one I should be using.
*I've seen a lot of threads mentioning file size could be an issue, and I'd like to point out that some files I'll be checking may be up to 4gb in size.
I've tried the following:
Dim bytes() As Byte = New Byte(OpenedFile.Length) {}
ListBox1.Items.Add(Conversion.Hex(OpenedFile.Read(bytes, &H2050, 6)))
But this simply writes 6 bytes to the file, and I'm not sure why. There is no output in the listbox.
How about something like the following?:
Sub Main()
Dim pos As Long = 8272
Dim requiredBytes As Integer = 2
Dim value(0 To requiredBytes - 1) As Byte
Using reader As New BinaryReader(File.Open("File.bin", FileMode.Open))
' Loop through length of file.
Dim fileLength As Long = reader.BaseStream.Length
Dim byteCount As Integer = 0
reader.BaseStream.Seek(pos, SeekOrigin.Begin)
While pos < fileLength And byteCount < requiredBytes
value(byteCount) = reader.ReadByte()
pos += 1
byteCount += 1
End While
End Using
Dim displayValue As String
displayValue = BitConverter.ToString(value)
End Sub
I have been trying my hand at handling packets and bytes for the first time, and I have not been able to obtain the packet length correctly so far after many different techniques.
Code:
Public Shared Sub Client(packet As Packet)
Console.WriteLine( _
"Client -> " & _
packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") & _
" length:" & Convert.ToString(packet.Length))
'Define Byte Array
Dim clientPacket As Byte() = packet.Buffer
' Open a Binary Reader
Dim memStream As MemoryStream = New MemoryStream(clientPacket)
Dim bReader As BinaryReader = New BinaryReader(memStream)
' Remove the Ethernet Header
Dim ethBytes As Byte() = bReader.ReadBytes(14)
' Remove the IPv4 Header
Dim IPv4Bytes As Byte() = bReader.ReadBytes(20)
' Remove the TCP Header
Dim TCPBytes As Byte() = bReader.ReadBytes(20)
' Get the packet length
If clientPacket.Length > 54 Then
Dim len As UInt32 = bReader.ReadUInt32
Console.WriteLine(len)
End If
End Sub
So far, all of my attempts at having the console write the data length have resulted in failure. I validated the endianness and actually wrote out the bytes to verify that I was handling the correct data.
Example bytes:
00 00 00 24 -> UINT32 is 36 bytes, but I am getting an array of Integers like 3808493568
How can I fix this?
I agree with Hans, endianness is your problem. Also, I'd recommend you use the BitConverter class on the clientPacket array, easier than using streams.
Dim len As UInt32
Dim arr() As Byte
arr = {0, 0, 0, 24}
len = BitConverter.ToUInt32(arr, 0)
Console.Write(len.ToString) 'returns 402653184
arr = {24, 0, 0, 0}
len = BitConverter.ToUInt32(arr, 0)
Console.Write(len.ToString) 'returns 24
For your code, I think this might work (untested):
If clientPacket.Length > 54 Then
Dim lenBytes As Byte() = bReader.ReadBytes(4)
Array.Reverse(lenBytes, 0, 4)
Dim len As UInt32 = BitConverter.ToUInt32(lenBytes, 0)
I have a piece of code that generates random characters. The problem is, every once in a while, it returns an error:
"startIndex cannot be larger than length of string.
Parameter name: startIndex"
How do I prevent this kind of error from happening?
Here's my code:
Friend Function gentCtrlChar()
Dim ran As New Random
Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim alpha2 As String = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
Dim rdm As New Random
Dim genChar As String = ""
For i As Integer = 1 To 52
Dim selChar As Integer = rdm.Next(1, 28)
Dim selChar2 As Integer = rdm.Next(1, 28)
genChar = genChar + "" + alpha.Substring(selChar, 1) + "" + alpha2.Substring(selChar2, 1)
On Error Resume Next
Exit For
Next
Return genChar
End Function
as you can see, I tried putting the "On Error Resume Next" hoping that somehow, this will take care of the error for me. But sadly, It doesn't do it's job. Or am I using it the wrong way or for the wrong situation?
Any help?
Thanks!
this code:
Dim selChar As Integer = rdm.Next(1, 28)
will sometimes return a number that is longer (27 or 28) than the length of this string:
Dim alpha As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" (only 26 characters long)
so, this is invalid when selChar is 26 or more.
alpha.Substring(selChar, 1)
Easiest fix is:
Dim selChar As Integer = rdm.Next(0, alpha.Length)
Dim selChar2 As Integer = rdm.Next(0, alpha2.Length)
Try this way. I think its cleaner and easy to understand. A - Z is the same as 65 - 90 on the ascii map so its very easy to convert an integer into a Char value. Then we just use the string builder to make this easier to read.
Dim rdm As New Random
Dim genChar As New StringBuilder()
For i As Integer = 1 To 52
Dim selChar As Char = Chr(rdm.Next(65, 90))
Dim selChar2 As Char = Chr(rdm.Next(65, 90))
genChar.Append(selChar)
genChar.Append(selChar2)
Next
Return genChar.ToString
well i know that there are a lot of these threads but im new to vb.net yet i cant edit the sources given to make what i really want
so i want a function that will generate random strings which will contain from 15-32 characters each and each of them will have the following chars ( not all at the same string but some of them ) :
A-Z
a-z
0-9
here is my code so far
Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Change the string to include the a-z characters:
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Change the loop to create a random number of characters:
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Note that the upper boundary in the Next method is exclusive, so Next(15, 33) gives you a value that can range from 15 to 32.
Use the length of the string to pick a character from it:
Dim idx As Integer = r.Next(0, s.Length)
As you are going to create random strings, and not a single random string, you should not create the random number generator inside the function. If you call the function twice too close in time, you would end up with the same random string, as the random generator is seeded using the system clock. So, you should send the random generator in to the function:
Function RandomString(r As Random)
So, all in all:
Function RandomString(r As Random)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim sb As New StringBuilder
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Usage example:
Dim r As New Random
Dim strings As New List<string>()
For i As Integer = 1 To 10
strings.Add(RandomString(r))
Next
Try something like this:-
stringToReturn&= Guid.NewGuid.ToString().replace("-","")
You can also check this:-
Sub Main()
Dim KeyGen As RandomKeyGenerator
Dim NumKeys As Integer
Dim i_Keys As Integer
Dim RandomKey As String
''' MODIFY THIS TO GET MORE KEYS - LAITH - 27/07/2005 22:48:30 -
NumKeys = 20
KeyGen = New RandomKeyGenerator
KeyGen.KeyLetters = "abcdefghijklmnopqrstuvwxyz"
KeyGen.KeyNumbers = "0123456789"
KeyGen.KeyChars = 12
For i_Keys = 1 To NumKeys
RandomKey = KeyGen.Generate()
Console.WriteLine(RandomKey)
Next
Console.WriteLine("Press any key to exit...")
Console.Read()
End Sub
Using your function as a guide, I modified it to:
Randomize the length (between minChar & maxCharacters)
Randomize the string produced each time (by using the static Random)
Code:
Function RandomString(minCharacters As Integer, maxCharacters As Integer)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(minCharacters, maxCharacters)
Dim sb As New StringBuilder
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
Return sb.ToString()
End Function
Try this out:
Private Function RandomString(ByRef Length As String) As String
Dim str As String = Nothing
Dim rnd As New Random
For i As Integer = 0 To Length
Dim chrInt As Integer = 0
Do
chrInt = rnd.Next(30, 122)
If (chrInt >= 48 And chrInt <= 57) Or (chrInt >= 65 And chrInt <= 90) Or (chrInt >= 97 And chrInt <= 122) Then
Exit Do
End If
Loop
str &= Chr(chrInt)
Next
Return str
End Function
You need to change the line For i As Integer = 1 To 8 to For i As Integer = 1 To ? where ? is the number of characters long the string should be. This changes the number of times it repeats the code below so more characters are appended to the string.
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
My $.02
Dim prng As New Random
Const minCH As Integer = 15 'minimum chars in random string
Const maxCH As Integer = 35 'maximum chars in random string
'valid chars in random string
Const randCH As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Private Function RandomString() As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To prng.Next(minCH, maxCH + 1)
sb.Append(randCH.Substring(prng.Next(0, randCH.Length), 1))
Next
Return sb.ToString()
End Function
please note that the
r.Next(0, 35)
tend to hang and show the same result Not sure whay; better to use
CInt(Math.Ceiling(Rnd() * N)) + 1
see it here Random integer in VB.NET
I beefed up Nathan Koop's function for my own needs, and thought I'd share.
I added:
Ability to add Prepended and Appended text to the random string
Ability to choose the casing of the allowed characters (letters)
Ability to choose to include/exclude numbers to the allowed characters
NOTE: If strictly looking for an exact length string while also adding pre/appended strings you'll need to deal with that; I left out any logic to handle that.
Example Usages:
' Straight call for a random string of 20 characters
' All Caps + Numbers
String_Random(20, 20, String.Empty, String.Empty, 1, True)
' Call for a 30 char string with prepended string
' Lowercase, no numbers
String_Random(30, 30, "Hey_Now_", String.Empty, 2, False)
' Call for a 15 char string with appended string
' Case insensitive + Numbers
String_Random(15, 15, String.Empty, "_howdy", 3, True)
.
Public Function String_Random(
intMinLength As Integer,
intMaxLength As Integer,
strPrepend As String,
strAppend As String,
intCase As Integer,
bIncludeDigits As Boolean) As String
' Allowed characters variable
Dim s As String = String.Empty
' Set the variable to user's choice of allowed characters
Select Case intCase
Case 1
' Uppercase
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Case 2
' Lowercase
s = "abcdefghijklmnopqrstuvwxyz"
Case Else
' Case Insensitive + Numbers
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
End Select
' Add numbers to the allowed characters if user chose so
If bIncludeDigits = True Then s &= "0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(intMinLength, intMaxLength)
Dim sb As New StringBuilder
' Add the prepend string if one was passed
If String.IsNullOrEmpty(strPrepend) = False Then sb.Append(strPrepend)
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
' Add the append string if one was passed
If String.IsNullOrEmpty(strAppend) = False Then sb.Append(strAppend)
Return sb.ToString()
End Function