VB.net console application to print Reverse of number - vb.net

I am trying to print reverse of number using VB.NET console application and I have variable of type Integer. when I give number 651 as input it prints 1561. I have write code as
Sub Main()
Dim no, rev, temp As Integer
Console.WriteLine("enter the no")
no = CInt(Console.ReadLine())
rev = 0
temp = no
While temp > 0
Dim t As Integer
t = temp Mod 10
rev = rev * 10 + t
temp = temp / 10
End While
Console.WriteLine("Reverse number=>"+rev.ToString())
Console.ReadKey()
End Sub
when I enter number 123 then it gives proper output as 321, but when i give 678,it give output 8761 or other garbage value, please suggest me suggetion

You are getting such result because,
when you assign a division result to an integer value it will
automatically get rounded to the next higher integer.
For example Dim no As Integer = 68 / 10 will give you result as 7,
if you are coding with Option Strict On then this casting is not allowed.
The best way is suggested by Bjørn-Roger Kringsjå you can simply reverse a number and print it.
Console.Write("Reverse of {0} is : ", no.ToString().Reverse())
or else you can follow the following steps:
Console.WriteLine("enter the no")
Dim no As Integer = CInt(Console.ReadLine())
Console.Write("Reverse of {0} is : ", no)
While no > 0
Console.Write(no Mod 10)
no = Math.Floor(no / 10)
End While
Console.ReadKey()

Just use \ instead of / and your work is done.

Related

Convert 32-bit signed integer to 64-bit integer while preserving the exact bits

I have a 32-bit value that is stored in the VB.Net type Integer (i.e. Int32.) I am only interested in the bits - not the numerical value. Sometimes the 32nd bit is a one which is interpreted as a negative number. My goal is to reverse the actual bits. My original data is encoded into bits right-to-left (LSB right-most) and is read back in left-to-right (MSB left-most.) I am adapting someone else's code and design. One thought I had was maybe to convert to a long temporarily but I don't know how to do that and preserve the 32nd bit correctly.
Public Shared Function ReverseBits32(ByVal n As Integer) As Integer
Dim result As Integer = 0
For i As Integer = 0 To 32 - 1
result = result * 2 + n Mod 2
n = n >> 1 'n Or 2
Next
Return result
End Function
If you had a method to reverse the bits of a byte you could apply it four times to the bytes of an integer. A little research finds Bit Twiddling Hacks.
Module Module1
Sub ShowBits(a As Integer)
Dim aa = BitConverter.GetBytes(a)
Console.WriteLine(String.Join(" ", aa.Select(Function(b) Convert.ToString(b, 2).PadLeft(8, "0"c))))
End Sub
Function ReverseBits(b As Byte) As Byte
' From https://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith32Bits
Dim c = CULng(b)
Return CByte((((c * &H802UL And &H22110UL) Or (c * &H8020UL And &H88440UL)) * &H10101UL >> 16) And &HFFUL)
End Function
Function ReverseBits(a As Integer) As Integer
Dim bb = BitConverter.GetBytes(a)
Dim cc(3) As Byte
For i = 0 To 3
cc(3 - i) = ReverseBits(bb(i))
Next
Return BitConverter.ToInt32(cc, 0)
End Function
Sub Main()
Dim y = -762334566
ShowBits(y)
y = ReverseBits(y)
ShowBits(y)
Console.ReadLine()
End Sub
End Module
Output from test value:
10011010 10110010 10001111 11010010
01001011 11110001 01001101 01011001
I used the "no 64-bit" method because it is written for a language where arithmetic overflow is ignored - the methods using 64-bit operations rely on that but it is not the default for VB.NET.

Add integer to another integer in vb.net?

How can I add an integer to another integer in vb.net?
This is what I need to do:
Given integer: 2187 ->
Converted integer: 2018
I need to add a 0 in between the first and second number, and drop the last digit. This will give me the year.
Here is the code that I have:
Protected Function GetYear(ByVal term As Integer) As Integer
Dim termYear As String = Convert.ToString(term)
termYear.Substring(0, 2)
termYear.Insert(1, "0")
Dim convertedYear As Integer
Int32.TryParse(termYear.ToString, convertedYear)
convertedYear = convertedYear / 10
Return convertedYear
End Function
In general strings are immutable. So you'd have to create a new string out of the addition of substrings. Check this possible solution.
Function GetYear(ByVal term As Integer) As Integer
Dim termYear As String = Convert.ToString(term, Globalization.CultureInfo.InvariantCulture)
Dim result As String = termYear.Substring(0, 1) + "0" + termYear.Substring(1, 2)
Return Int32.Parse(result)
End Function
Strings are immutable, when you do any changes with one of their method, you need to get the returned string.
termYear = termYear.Insert(1, "0")
This question deserves a math based solution. The below code specifies the zero insertion point relative to the number's right side instead of the left as stated in the problem statement. So for a 4 digit number the insertion point is 3 versus 2. It also allows you to change the insertion point.
Private Function GetYear(ByVal term As Integer, Optional zeroDigitPosition As Integer = 3) As Integer
If zeroDigitPosition > 0 Then
Dim divisor As Integer = 1
For i As Integer = 1 To zeroDigitPosition - 1
divisor *= 10
Next
Dim ret As Integer = term \ 10 ' drop one's place digit, remaining digits shift to right
Dim rightShiftedDigits As Integer = ret Mod divisor
Dim remainder As Integer = Math.DivRem(ret, divisor, rightShiftedDigits)
' shift the remainder to the left by divisor * 10
' (remember first right shift invplved \ 10) and add
' rightShiftedDigits to yield result
Return (remainder * divisor * 10) + rightShiftedDigits
Else
Throw New ArgumentOutOfRangeException("zeroDigitPosition must be greater then zero")
End If
End Function

Trying to shorten code in VB.NET

One of my assignments in vb.net is to make a program that takes in 15 inputted "test scores", returns the average, and then returns the corresponding letter grade. I am trying to make this as short as possible, and I remembered a code format that I can use when I am coding in Python (simple example with only three scores):
counter = 0
number = 0
test1,test2,test3 = 0,0,0
for i in [test1,test2,test3]:
print("Enter a test score")
i = int(input())
counter += i
number += 1
average = counter/number
Is there such a code format in VB.NET?
Yes.
Here is a simple sample code which asks user to input number of items and then items one by one. At the end it calculates average of numbers.
Console.WriteLine("Enter number of Items")
Dim numberOfItems As Integer
If Integer.TryParse(Console.ReadLine(), numberOfItems) Then
Dim items As New List(Of Decimal)()
For i As Integer = 1 To numberOfItems
Console.WriteLine("Enter number {0}", i)
Dim num As Decimal
If Decimal.TryParse(Console.ReadLine(), num) Then
items.Add(num)
End If
Next
Console.WriteLine("Average is " + items.Average())
Console.ReadLine()
End If
Please note that I've not included any type of error handling.

How can I find the average of all numbers in a textfile

I'm ridiculously stuck on this one. My code below sums up all the numbers that are in the textfile Dailyfile and outputs the total to AverageFile. The problem is I don't want it to sum up. I want it to find out the average of all the numbers.
How can I do this?
Dim AverageFile As String = "C:\xxx\zzz\" & System.DateTime.Now.ToString("yyyyMMdd") & ".txt"
Dim DailyFile As String = "C:\xxx\xxx\" & System.DateTime.Now.ToString("yyyyMMdd") & ".txt"
Try
If System.IO.File.Exists(AverageFile) Then
Dim total As double = 0
For Each line As String In IO.File.ReadAllLines(DailyFile)
total += Double.Parse(line)
Next
Dim objWriter As New System.IO.StreamWriter(AverageFile, false)
objWriter.WriteLine(total.ToString)
objWriter.Close()
Else
'Nothing yet
End If
Catch ex As Exception
lbErrors.Items.Add(String.Concat(TimeOfDay & " Error 98: File or folder might not exist. Restart application... ", ex.Message))
End Try
The Dailyfile simply looks like this;
I've tried a bunch of variations on the total 0= double.parse(line), because I feel like thats where the problem lies. I've also tried diming the total as integer = 0. I'm new to the calculating, so I don't know how things go.
The average is just the total divided by the number of things you summed up. (Assuming you want to use the arithmetic mean, which is probably what you are looking for.)
Dim total As double = 0
Dim numOfLines As Integer = 0
For Each line As String In IO.File.ReadAllLines(DailyFile)
numOfLines += 1
total += Double.Parse(line)
Next
Dim average As Double = total / numOfLines
Dim objWriter As New System.IO.StreamWriter(AverageFile, false)
objWriter.WriteLine(average.ToString)
objWriter.Close()
What was missing in your code is just keeping track of the number of lines and dividing the sum by this number.
Just as an example: We are 3 people. I am 23 years old, you are 35 years old, our friend is 40 years old. The average of our ages would be (23 + 35 + 40) / 3 which is 32.666...
Either use CherryDT's approach to count the lines and divide the total through this number or use LINQ's Enumerable.Average, for example with this concise query:
Dim allNumbers = From line In IO.File.ReadLines(DailyFile)
Let num = line.TryGetDouble()
Where num.HasValue
Select num.Value
Dim average As Double = allNumbers.Average()
I've used following extension method to try-parse the string to a Nullable(Of Double):
Imports System.Runtime.CompilerServices
Module StringExtensions
<Extension()>
Public Function TryGetDouble(ByVal str As String) As Nullable(Of Double)
If str Is Nothing Then Return Nothing
Dim d As Double
If Double.TryParse(str.Trim(), d) Then
Return d
Else
Return Nothing
End If
End Function
End Module

How do you convert a string into hexadecimal in VB.NET?

How do I convert a string from a textbox into hexadecimal?
I have only found ways in C#. Does VB.NET have the ability to do such a thing? If it can then I'd like to know how to convert string to hex and hex to string.
Dim val As String
val = "10"
Dim hexVal As Integer
hexVal = Convert.ToInt32(val, 16) //16 specifies the base
Console.WriteLine(hexVal)
This will display 16 which is the integer equivalent of the hexadecimal string "10".
You can convert an integer to a hexdecimal number easily by doing:
Convert.ToInt32(15, 16)
And to convert it back to an integer, you can do:
Integer.Parse("15f", System.Globalization.NumberStyles.HexNumber)
Public Function StrToHex(ByRef Data As String) As String
Dim sVal As String
Dim sHex As String = ""
While Data.Length > 0
sVal = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()))
Data = Data.Substring(1, Data.Length - 1)
sHex = sHex & sVal
End While
Return sHex
End Function
Tried and tested code
Create this function by copy pasting it.
Function StringToHex(ByVal text As String) As String
Dim hex As String
For i As Integer = 0 To text.Length - 1
hex &= Asc(text.Substring(i, 1)).ToString("x").ToUpper
Next
Return hex
End Function
Use it like this
Debug.WriteLine(StringToHex("sim0n"))
Source
To convert into hexadecimal, use Convert.ToInt32(val, 16). Convert.ToInt32 supports limited bases, 2, 8, 10, and 16.
To convert into any base, use:
Public Shared Function IntToString(value As Integer, baseChars As Char()) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) + result
value = value / targetBase
Loop While value > 0
Return result
End Function
The above function comes from this question. The C# to VB conversion was done using this.
Short and effective expression to display all characters of String s in hexadecimal form can be written using LINQ:
String.Join(" ", s.Select(Function(c) Conversion.Hex(AscW(c)).PadLeft(4, "0")).ToArray()))
Example:
For string ► fix it gives string 25BA 0020 0066 0069 0078.
Enjoy!
Please keep in mind this is Unicode-enabled, returning 4-digit hexadecimal value for every character, because old plain Non-Unicode ASCII is dead and you should no longer rely on it in any application.
In my humble opinion the code of Tilak seems OK, but is not.
The rounding of value / targetBase gives results that are too large.
By using Fix() the resulting integers will be as they should be.
I compliment Tilak for finding such a neat solution for the question.
In the accompanying code I will show how functions like IntToString can be tested easily.
The expected message in the message box is:
The old results are;
0 1 10 101 100 101 1010 1001 1000 1001 1010
0 1 1X 10 11 1XX 1X0 1X1 10X 100 101
0 1 X 1y 10 11 XX Xy X0 X1 XX
0 1 X 1y 1z 10 11 1X Xy Xz X0
The new results are;
0 1 10 11 100 101 110 111 1000 1001 1010
0 1 X 10 11 1X X0 X1 XX 100 101
0 1 X y 10 11 1X 1y X0 X1 XX
0 1 X y z 10 11 1X 1y 1z X0
The new results are better IMHO.
Public Sub test()
Dim numberCharacters As String = "01Xyz"
Dim messageText As String = "The old results are;" & vbNewLine
For loopCount As Integer = 1 To 2
If loopCount = 2 Then messageText &= "The new results are;" & vbNewLine
For baseLength As Integer = 2 To 5
Dim baseCharacters As Char() = _
Strings.Left(numberCharacters, baseLength).ToArray
For integerValue As Integer = 0 To 10
Dim resultText As String = _
Me.IntToString(integerValue, baseCharacters, loopCount = 2)
messageText &= resultText & " "
Next
messageText &= vbNewLine
Next
Next
Call MsgBox(berichtTekst & "The new results are better IMHO.")
End Sub
Public Function IntToString(value As Integer, baseChars As Char(), _
Optional newCode As Boolean = False) As String
Dim result As String = String.Empty
Dim targetBase As Integer = baseChars.Length
Do
result = baseChars(value Mod targetBase) & result
If newCode Then ' Improved code
value = Fix(value / targetBase)
Else ' Original code
value = value / targetBase
End If
Loop While value > 0
Return result
End Function
Hopefully this will help others.
I have more than 25 years experience as a programmer, mainly in RPG, Cobol, Synon, CL and Basic. I also know some Delphi, Pascal and C#. I am sure I can be a help to this community.
It makes me sad that I cannot comment to answers. Hopefully someone will add me some points, so that I can more easily help others from now on.
Because of this I add my comment to the answer of Tilak, dated may 8, 2012, as an answer. This is the first and hopefully the only time that I resort to this. Sorry for that, but I know no other way.