Need VB code commented to convert it to Java - vb.net

I am a Java developer. I have the task of converting a VB class to Java.
Can some VB developer comment the following VB code so that I can write its Java equivalent?
Public Class RmaValidationCode
' Values for test type
Public Const SOFTWARE_TEST_TYPE = 0
Public Const FIRMWARE_TEST_TYPE = 1
' Values for test length
Public Const SHORT_TEST_LENGTH = 0
Public Const LONG_TEST_LENGTH = 1
' Values for test result
Public Const PASS_TEST_RESULT = 0
Public Const FAIL_TEST_RESULT = 1
Public Const ABORT_TEST_RESULT = 2
Public Const CAUTION_TEST_RESULT = 3
' GetRMAValidationCode function bit mapped return values
Public Const RMA_VC_RET_PASS = 0
Public Const RMA_VC_RET_NULL_PTR_PARAMETER = 1
Public Const RMA_VC_RET_INVALID_STR_LENGTH = 2
Public Const RMA_VC_RET_INVALID_SN_STRING = 4
Public Const RMA_VC_RET_INVALID_TEST_TYPE = 8
Public Const RMA_VC_RET_INVALID_TEST_LENGTH = 16
Public Const RMA_VC_RET_INVALID_TEST_RESULT = 32
Private Const RMA_LENGTH = 8
Private rmaValidationCode As String
' This function will return the warranty validation code based on serial number, test type,
' test result, test software and test length.
' Test type - Generic=0, DST=1
' Test result - Pass=0, FAIL=1
' Test Software - DOS=0, Windows=1
' Test Length - Short=0 Long=1
Public Function GetRMAValidationCode(ByVal serialNumber As String, ByVal testType As Byte, _
ByVal testResult As Byte, ByVal testSoftware As Byte, ByVal testLength As Byte)
Dim returnValue As UInt32
Dim tempRMACode As String
Dim tempRMAEnumerator As CharEnumerator
Dim temp8Bit As Byte
returnValue = RMA_VC_RET_PASS
temp8Bit = 0
' Make sure we were passed valid strings
If String.IsNullOrEmpty(serialNumber) OrElse _
String.IsNullOrEmpty(rmaValidationCode) Then
returnValue = returnValue Or RMA_VC_RET_NULL_PTR_PARAMETER
End If
' Make sure our strings are big enough
If serialNumber.Length < RMA_LENGTH OrElse _
rmaValidationCode.Length < RMA_LENGTH Then
returnValue = returnValue Or RMA_VC_RET_INVALID_STR_LENGTH
End If
' Assure that valid test types were passed in
If testType <> SOFTWARE_TEST_TYPE AndAlso _
testType <> FIRMWARE_TEST_TYPE Then
returnValue = returnValue Or RMA_VC_RET_INVALID_TEST_TYPE
End If
' Assure that valid test lengths were passed in
If testLength <> SHORT_TEST_LENGTH AndAlso _
testLength <> LONG_TEST_LENGTH Then
returnValue = returnValue Or RMA_VC_RET_INVALID_TEST_LENGTH
End If
' Assure that valid test results were passed in
If testResult <> PASS_TEST_RESULT AndAlso _
testResult <> FAIL_TEST_RESULT AndAlso _
testResult <> ABORT_TEST_RESULT AndAlso _
testResult <> CAUTION_TEST_RESULT Then
returnValue = returnValue Or RMA_VC_RET_INVALID_TEST_RESULT
End If
If returnValue = RMA_VC_RET_PASS Then
' Trim leading and trailing whitespace
serialNumber.Trim()
' Check to see if the serialNumber string is long enough
' after whitespace is removed
If serialNumber.Length < RMA_LENGTH Then
Return RMA_VC_RET_INVALID_SN_STRING
End If
tempRMACode = serialNumber.ToLower()
tempRMAEnumerator = tempRMACode.GetEnumerator()
While (tempRMAEnumerator.MoveNext())
If Not Char.IsLetterOrDigit(tempRMAEnumerator.Current) Then
Return RMA_VC_RET_INVALID_SN_STRING
End If
End While
' Initialize the rmaValidationCode
rmaValidationCode = ""
' Compute and save the first 6 bytes of RMA Validation Code
temp8Bit = 0
temp8Bit = Convert.ToByte(tempRMACode.ToCharArray().GetValue(0)) + Convert.ToByte((tempRMACode.ToCharArray()).GetValue(7))
rmaValidationCode += String.Format("{0:X2}", temp8Bit)
temp8Bit = 0
temp8Bit = Convert.ToByte((tempRMACode.ToCharArray()).GetValue(1)) + Convert.ToByte((tempRMACode.ToCharArray()).GetValue(6))
rmaValidationCode += String.Format("{0:X2}", temp8Bit)
temp8Bit = 0
temp8Bit = Convert.ToByte((tempRMACode.ToCharArray()).GetValue(2)) + Convert.ToByte((tempRMACode.ToCharArray()).GetValue(5))
rmaValidationCode += String.Format("{0:X2}", temp8Bit)
' Byte 6 is the Test & Result byte.
temp8Bit = 0
temp8Bit = (testSoftware << 3) Or (testResult << 2) Or (testType << 1) Or testLength
rmaValidationCode += String.Format("{0:X1}", temp8Bit)
' Compute the parity byte
temp8Bit = 0
Dim mychar As Char
mychar = rmaValidationCode.ToCharArray().GetValue(3)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(3), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or (1 << 3)
Else
temp8Bit = temp8Bit Or (0 << 3)
End If
Dim value As Integer
mychar = rmaValidationCode.ToCharArray().GetValue(2)
value = System.Convert.ToInt32(mychar, 16)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(2), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or (1 << 2)
Else
temp8Bit = temp8Bit Or (0 << 2)
End If
mychar = rmaValidationCode.ToCharArray().GetValue(1)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(1), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or (1 << 1)
Else
temp8Bit = temp8Bit Or (0 << 1)
End If
mychar = rmaValidationCode.ToCharArray().GetValue(0)
If ((Convert.ToInt32(rmaValidationCode.ToCharArray().GetValue(0), 16) Mod 2) = 1) Then
temp8Bit = temp8Bit Or 1
Else
temp8Bit = temp8Bit Or 0
End If
rmaValidationCode += String.Format("{0:X1}", temp8Bit)
End If
Return rmaValidationCode
End Function
Public Sub New()
' serialNumber = " "
rmaValidationCode = " "
' testType = 0
'testLength = 0
'testResult = 0
End Sub
End Class

Actually that is pretty readable and straightforward code. You may want to take a look at VB keywords as well as the AndAlso/OrElse operators (those two sometimes confuse C-style language developers). The rest that's used are just plain old .NET class library methods. Nothing too fancy and you'll find plenty of documentation about those on MSDN.

Unfortunately you're not going to find anyone here that will comment the above code for free.
Visual Basic syntax is relatively simple - it was designed as an entry level language. If you engage your mind and read over the general key words such as AndAlso OrElse WhileNot etc, you shouldn't have a massive issue commenting it yourself.
If you were further interested in the way the code works - the way I usually learn to understand X piece of code is to go step - by - step through it until I finally get the gist of it.
Try searching MSDN for any keywords you don't fully understand.

Related

How can I get result from string formula as integer

How I can get result value from this string formula :
Dim Formula As String
Formula = "((5000 / 30) * (22 + 6)) + ((5000 / 30 / 8) * (20))"
Dim Result As Integer
Result = ?????
How can I get an integer result value? It's 5083.33
A bit simpler - use the .Compute method of the DataTable
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim r = dt.Compute("((5000 / 30) * (22 + 6)) + ((5000 / 30 / 8) * (20))", Nothing)
Debug.Print(r.ToString)
End Sub
Result in Immediate Window
5083.33333333333
Thanks every body,
I got the CODE right now as following :-
Just you Can Do ..... >>> NumericBox1 = EvaluateExpr(TextBox2.Text)
Private Function IsEmptyStack(ByVal AStack As Stack) As Boolean
Return (AStack.Count = 0)
End Function
Private Function IsOperator(ByVal AChar As Char) As Boolean
Return "^*/+-".Contains(AChar)
End Function
Private Function CompareOperators(ByVal Op1 As Char, ByVal Op2 As Char) As Integer
If Not (IsOperator(Op1) And IsOperator(Op2)) Then
Err.Raise(vbObjectError + 1001, "CompareOperators", "Operator(s) not suppoerted")
End If
Select Case Op1
Case "^"c
If Op2 = "^"c Then
Return 0
Else
Return 1
End If
Case "*"c, "/"c
Select Case Op2
Case "^"c
Return -1
Case "*"c, "/"c
Return 0
Case "+"c, "-"c
Return 1
End Select
Case "+"c, "-"c
Select Case Op2
Case "^"c, "*"c, "/"c
Return -1
Case "+"c, "-"c
Return 0
End Select
End Select
End Function
Private Function InfixToPostfix(ByVal InfixExpression As String) As String
Dim Infix As String
Dim Postfix As String
Dim InfixIndex As Integer
Dim InfixLen As Integer
Dim AChar As Char
Dim APeek As String
Dim ANumber As String
Dim MathStack As New Stack
Infix = InfixExpression.Trim()
If Infix = "" Then
Return ""
End If
Infix = Infix & ")"
ANumber = ""
Postfix = ""
InfixLen = Len(Infix) '- 1
InfixIndex = 0
MathStack.Clear()
MathStack.Push("(")
Do While (Not IsEmptyStack(MathStack)) And (InfixIndex <= InfixLen)
'AChar = Mid$(Infix, InfixIndex, 1)
AChar = Infix(InfixIndex)
If Char.IsDigit(AChar) Then
ANumber = ANumber & AChar
ElseIf AChar = "(" Then
If ANumber <> "" Then
Postfix = Postfix & ANumber & " "
ANumber = ""
End If
MathStack.Push(AChar)
ElseIf IsOperator(AChar) Then
If ANumber <> "" Then
Postfix = Postfix & ANumber & " "
ANumber = ""
End If
APeek = MathStack.Peek
If IsOperator(APeek) Then
Do While CompareOperators(APeek, AChar) >= 0
APeek = MathStack.Pop
Postfix = Postfix & APeek
APeek = MathStack.Peek
If Not IsOperator(APeek) Then Exit Do
Loop
End If
MathStack.Push(AChar)
ElseIf AChar = ")" Then
If ANumber <> "" Then
Postfix = Postfix & ANumber & " "
ANumber = ""
End If
APeek = MathStack.Peek
Do While APeek <> "("
APeek = MathStack.Pop
Postfix = Postfix & APeek
APeek = MathStack.Peek
Loop
MathStack.Pop()
End If
InfixIndex = InfixIndex + 1
Loop
If Not IsEmptyStack(MathStack) Then
Err.Raise(vbObjectError + 1002, "InfixToPostfix", "Invalid infix expression")
Else
InfixToPostfix = Postfix
End If
End Function
Private Function PerformOperation(ByVal Number1 As Double, ByVal Number2 As Double, ByVal AOperator As Char) As Double
Select Case AOperator
Case "+"c
Return Number1 + Number2
Case "-"c
Return Number1 - Number2
Case "*"c
Return Number1 * Number2
Case "/"c
If Number2 = 0 Then
Err.Raise(vbObjectError + 1004, "EvaluatePostfix", "Division by zero")
Else
Return Number1 / Number2
End If
Case "^"c
Return Number1 ^ Number2
Case Else
Err.Raise(vbObjectError + 1001, "CompareOperators", "Operator not suppoerted")
End Select
End Function
Private Function EvaluatePostfix(ByVal PostfixExpression As String) As Double
Dim Postfix As String
Dim ANumber As String
Dim AChar As Char
Dim PostfixIndex As Long
Dim PostfixLen As Long
Dim Num1 As Double
Dim Num2 As Double
Dim NumResult As Double
Dim MathStack As New Stack
Postfix = Trim$(PostfixExpression)
If Postfix = "" Then
Return 0.0
End If
Postfix = Postfix & "="
ANumber = ""
PostfixLen = Len(Postfix)
PostfixIndex = 0
MathStack.Clear()
Do While PostfixIndex <= PostfixLen
AChar = Postfix(PostfixIndex)
If AChar = " " Then
If ANumber <> "" Then
MathStack.Push(CDbl(ANumber))
ANumber = ""
End If
ElseIf Char.IsDigit(AChar) Then
ANumber = ANumber & AChar
ElseIf AChar = "=" Then
If ANumber <> "" Then
MathStack.Push(CDbl(ANumber))
ANumber = ""
End If
If MathStack.Count = 1 Then
Return MathStack.Pop
Else
Err.Raise(vbObjectError + 1003, "EvaluatePostfix", "Invalid postfix expression")
End If
ElseIf IsOperator(AChar) Then
If ANumber <> "" Then
MathStack.Push(CDbl(ANumber))
ANumber = ""
End If
If IsEmptyStack(MathStack) Then
Err.Raise(vbObjectError + 1003, "EvaluatePostfix", "Invalid postfix expression")
Else
Num2 = MathStack.Pop
If IsEmptyStack(MathStack) Then
Err.Raise(vbObjectError + 1003, "EvaluatePostfix", "Invalid postfix expression")
Else
Num1 = MathStack.Pop
NumResult = PerformOperation(Num1, Num2, AChar)
MathStack.Push(NumResult)
End If
End If
End If
PostfixIndex = PostfixIndex + 1
Loop
End Function
Public Function EvaluateExpr(ByVal AExpr As String) As String
Dim PostfixExpr As String
AExpr = AExpr.Trim
If AExpr = "" Then Return ""
PostfixExpr = InfixToPostfix(AExpr)
Return EvaluatePostfix(PostfixExpr)
End Function
This shouldn't really qualify as an answer, but I thought it would be fun to re-write that big code block using more modern techniques. I've done this right in the reply window, so there are probably several errors. It's worth noting, though, how much shorter this is.
We could have even more fun, and probably perform better, by also re-writing the code to think in terms of breaking apart the string into tokens, rather than by character.
Public Module Math
'Reverse precedence order, so higher precedence has higher index
Private operators As String = "-+/*^"
Private Function CompareOperators(Op1 As Char, Op2 As Char) As Integer
Dim Op1Value As Integer = operators.IndexOf(Op1)
Dim Op2Value As Integer = operators.IndexOf(Op2)
If Op1Value = -1 Then Throw New Exception($"Unsupported operator {Op1} detected")
If Op2Value = -1 Then Throw New Excpetion($"Unsupported operator {Op2} detected")
'The \ 2 adjusts for same precedence of +- and */
Return (Op1Value \ 2).CompareTo(Op2Value \ 2)
End Function
Private Function InfixToPostfix(InfixExpression As String) As String
If String.IsNullOrWhitesapce(InfixExpression) Then Return ""
InfixExpression = InfixExpression.Trim() & ")"
Dim result As New StringBuilder()
Dim MathStack As New Stack(Of Char)()
Dim ANumber As String = ""
Dim Index As Integer = 0
MathStack.Push("("c)
While MathStack.Count > 0 AndAlso Index <= InfixExpression.Length)
Dim AChar As Char = InfixExpression(Index)
If Char.IsDigit(AChar) Then
ANumber &= ANumber & AChar
ElseIf AChar = "("c Then
If Not String.IsNullOrEmpty(ANumber) Then
result.Append(ANumber).Append(" ")
ANumber = ""
End If
MathStack.Push(AChar)
ElseIf IsOperator(AChar) Then
If Not String.IsNullOrEmpty(ANumber) Then
result.Append(ANumber).Append(" ")
ANumber = ""
End If
Dim APeek As Char = MathStack.Peek()
If IsOperator(APeek) Then
While CompareOperators(APeek, AChar) >= 0
APeek = MathStack.Pop()
result.Append(APeek)
APeek = MathStack.Peek
If Not IsOperator(APeek) Then Exit While
End While
End If
MathStack.Push(AChar)
ElseIf AChar = ")"c Then
If Not String.IsNullOrEmpty(ANumber) Then
result.Append(ANumber).Append(" ")
ANumber = ""
End If
APeek = MathStack.Peek()
While APeek <> "("c
APeek = MathStack.Pop()
result.Append(APeek)
APeek = MathStack.Peek()
End While
MathStack.Pop()
End If
Index += 1
End While
If MathStack.Count > 0 Then
Throw New Exception("Invalid infix expression: stack is not empty")
End If
Return result.ToString()
End Function
Private Function PerformOperation(Number1 As Double, Number2 As Double, AOperator As Char) As Double
Select Case AOperator
Case "+"c
Return Number1 + Number2
Case "-"c
Return Number1 - Number2
Case "*"c
Return Number1 * Number2
Case "/"c
'We could detect Number2 = 0 here, but appropriate response is throwing the same DivideByZeroException the framework will do for us anyway
Return Number1 / Number2
Case "^"c
Return Number1 ^ Number2
Case Else
Throw New Exception($"Operator {AOperator} not supported")
End Select
End Function
Private Function EvaluatePostfix(Expression As String) As Double
Dim result As Double = 0R
If String.IsNullOrWhitespace(Expression) Then Return result
Expression = Expression.Trim() & "="
Dim MathStack As New Stack(Of Double)()
Dim ANumber As String = ""
Dim Index As Integer = 0
Do While Index <= Expression.Length
AChar = Expression(Index)
If AChar = " "c Then
If Not String.IsNullOrEmpty(ANumber) Then
MathStack.Push(CDbl(ANumber))
ANumber = ""
End If
ElseIf Char.IsDigit(AChar) Then
ANumber = ANumber & AChar
ElseIf AChar = "="c Then
If Not String.IsNullOrEmpty(ANumber) Then
MathStack.Push(CDbl(ANumber))
ANumber = ""
End If
If MathStack.Count = 1 Then Return MathStack.Pop()
Throw New Exception("Invalid postfix expression")
ElseIf IsOperator(AChar) Then
If Not String.IsNullOrEmpty(ANumber) Then
MathStack.Push(CDbl(ANumber))
ANumber = ""
End If
If MathStack.Count < 2 Then
Throw New Exception("Invalid postfix expression: insufficient stack")
End If
Dim Num2 As Double = MathStack.Pop()
MathStack.Push(PerformOperation(MathStack.Pop(), Num2))
End If
Index += 1
Loop
End Function
Public Function EvaluateExpr(AExpr As String) As String
If String.IsNullOrWhitespacE(AExpr) Then Return ""
Return EvaluatePostfix(InfixToPostfix(AExpr))
End Function
End Module
Wanted to do the token option for more fun:
Public Module Math
'Reverse precedence order, so higher precedence has higher index
Private operators As String = "()-+/*^"
Private Function IsOperator(AChar As Char) As Boolean
Return operators.Contains(AChar)
End Function
Private Function CompareOperators(Op1 As Char, Op2 As Char) As Integer
Dim Op1Value As Integer = operators.IndexOf(Op1)
Dim Op2Value As Integer = operators.IndexOf(Op2)
If Op1Value = -1 Then Throw New Exception($"Unsupported operator '{Op1}' detected")
If Op2Value = -1 Then Throw New Exception($"Unsupported operator '{Op2}' detected")
'The \ 2 adjusts for same precedence of +- and */
Return (Op1Value \ 2).CompareTo(Op2Value \ 2)
End Function
Private Iterator Function Tokenize(input As String) As IEnumerable(Of String)
Dim buffer As String = ""
For Each c As Char In input
If Char.IsWhitespace(c) Then
If String.IsNullOrEmpty(buffer) Then Continue For
Yield buffer
buffer = ""
ElseIf Char.IsDigit(c) OrElse c = "."c Then
buffer &= c 'Don't worry about validating good numbers at this level. Just check the characters
ElseIf c = "-"c Then ' could be operator or negative sign
If buffer.Length > 0 Then 'was an operator
Yield buffer
buffer = ""
Yield c.ToString()
Else 'Not sure yet -- treat as digit for now
buffer &= c
End If
ElseIf operators.Contains(c) OrElse "()".Contains(c) Then
If buffer.Length > 0 Then
Yield buffer
buffer = ""
End If
Yield c.ToString()
Else
Throw New Exception($"Unexpected character '{c}' in input")
End If
Next c
If buffer.Length > 0 Then Yield buffer
End Function
Private Iterator Function InfixToPostfix(tokens As IEnumerable(Of String)) As IEnumerable(Of String)
Dim buffer As New Stack(Of String)()
Dim temp As Double
For Each token As String In tokens
If Double.TryParse(token, temp) Then
Yield token
'Need to account for "(" better
ElseIf token = "(" Then
buffer.Push(token)
ElseIf operators.Contains(token) AndAlso token <> ")" Then
If buffer.Count = 0 Then
buffer.Push(token)
ElseIf CompareOperators(token, buffer.Peek()) > 0 Then
buffer.Push(token)
Else
While CompareOperators(token, buffer.Peek()) <= 0
Dim tok As String = buffer.Pop()
If Not "()".Contains(tok) Then Yield tok
If buffer.Count = 0 Then Exit While
End While
buffer.Push(token)
End If
ElseIf token = ")" Then
Dim valid As Boolean = False
While buffer.Count > 0
Dim tok As String = buffer.Pop()
If tok = "(" Then
valid = True
Exit While
Else
Yield tok
End If
End While
If Not valid Then Throw New Exception("Unbalanced parentheses in expression (missing matching '(' character)")
Else
Throw New Exception($"Unknown token type '{token}'")
End If
Next token
While buffer.Count > 0
Dim tok As String = buffer.Pop()
If Not "()".Contains(tok) Then Yield tok
End While
End Function
Private Function PerformOperation(Number1 As Double, Number2 As Double, AOperator As Char) As Double
Select Case AOperator
Case "+"c
Return Number1 + Number2
Case "-"c
Return Number1 - Number2
Case "*"c
Return Number1 * Number2
Case "/"c
'We could detect Number2 = 0 here, but appropriate response is throwing the same DivideByZeroException the framework will do for us anyway
Return Number1 / Number2
Case "^"c
Return Number1 ^ Number2
Case Else
Throw New Exception($"Operator {AOperator} not supported")
End Select
End Function
Private Function EvaluatePostfix(tokens As IEnumerable(Of String)) As Double
Dim result As Double = 0R
Dim buffer As New Stack(Of Double)()
Dim temp As Double
For Each token As String In tokens
If Double.TryParse(token, temp) Then
buffer.Push(temp)
ElseIf buffer.Count < 2 Then
Throw New Exception("Invalid postfix expression")
Else
temp = buffer.Pop()
temp = PerformOperation(buffer.Pop(), temp, token(0))
buffer.Push(temp)
End If
Next token
If buffer.Count > 1 Then Throw New Exception("Invalid expression: extra items in the buffer")
If buffer.Count = 0 Then Throw New Exception("Invalid expression: no result")
Return buffer.Pop()
End Function
Public Function Evaluate(input As String) As Double
If String.IsNullOrWhiteSpace(input) Then Return 0R
Dim tokens = Tokenize(input)
tokens = InfixToPostfix(tokens)
Return EvaluatePostfix(tokens)
End Function
End Module

Converting arabic numerals to roman numerals in a visual basic console application [duplicate]

Is it possible to use Format function to display integers in roman numerals?
For Counter As Integer = 1 To 10
Literal1.Text &= Format(Counter, "???")
Next
This is what I found on http://www.source-code.biz/snippets/vbasic/7.htm
(originally written by Mr Christian d'Heureuse in VB)
I converted it to VB.net:
Private Function FormatRoman(ByVal n As Integer) As String
If n = 0 Then FormatRoman = "0" : Exit Function
' there is no Roman symbol for 0, but we don't want to return an empty string
Const r = "IVXLCDM" ' Roman symbols
Dim i As Integer = Math.Abs(n)
Dim s As String = ""
For p As Integer = 1 To 5 Step 2
Dim d As Integer = i Mod 10
i = i \ 10
Select Case d ' format a decimal digit
Case 0 To 3 : s = s.PadLeft(d + Len(s), Mid(r, p, 1))
Case 4 : s = Mid(r, p, 2) & s
Case 5 To 8 : s = Mid(r, p + 1, 1) & s.PadLeft(d - 5 + Len(s), Mid(r, p, 1))
Case 9 : s = Mid(r, p, 1) & Mid(r, p + 2, 1) & s
End Select
Next
s = s.PadLeft(i + Len(s), "M") ' format thousands
If n < 0 Then s = "-" & s ' insert sign if negative (non-standard)
FormatRoman = s
End Function
I hope this will help others.
Cheers - Dave.
No, there is no standard formatter for that.
If you read the Wikipedia on Roman numerals you'll find that there are multiple ways of formatting Roman Numerals. So you will have to write your own method our use the code of someone else.
I wrote this code that works perfectly up to a million.
You can use it but, please, do not make it your own.
Public NotInheritable Class BRoman
'Written by Bernardo Ravazzoni
Public Shared Function hexRoman(ByVal input As Integer) As String
Return mainROMAN(input)
End Function
Private Shared Function mainROMAN(ByVal input As Integer) As String
Dim under As Boolean = udctr(input)
Dim cifretotali As Integer = input.ToString.Length
Dim output As String = ""
Dim remaning As String = input
Dim cifracor As Integer = cifretotali
While Not cifracor = 0
output = output & coreROMAN(division(remaning, remaning), cifracor)
cifracor = cifracor - 1
End While
If under Then
output = "-" & output
End If
Return output
End Function
Private Shared Function coreROMAN(ByVal num As Integer, ByVal pos As Integer) As String
Dim output As String = ""
Debug.WriteLine(num)
Select Case num
Case 1 To 3
output = say(num, getStringFor(True, pos))
Case 4
output = getStringFor(True, pos) & getStringFor(False, pos)
Case 5 To 8
output = getStringFor(False, pos) & say(num - 5, getStringFor(True, pos))
Case 9, 10
output = say(10 - num, getStringFor(True, pos)) & getStringFor(True, pos + 1)
End Select
Return output
End Function
Private Shared Function getStringFor(ByVal first As Boolean, ByVal index As Integer) As String
Dim output As String = ""
index = index * 2
If first Then
index = index - 1
End If
output = rGetStringFor(index)
Return output
End Function
Private Shared Function rGetStringFor(ByVal index As Integer) As String
Dim output As String = ""
Dim sy As Integer
If index < 8 Then
output = rrGetStringFor(index)
Else
sy = index \ 6
output = say(sy, rrGetStringFor(8)) & rrGetStringFor(((index - 2) Mod 6) + 2) & say(sy, rrGetStringFor(9))
End If
Return output
End Function
Private Shared Function rrGetStringFor(ByVal index As Integer) As String
Dim output As String = ""
Select Case index
Case 1
output = "I"
Case 2 '8
output = "V"
Case 3 '9
output = "X"
Case 4 '10
output = "L"
Case 5 '11
output = "C"
Case 6 '12
output = "D"
Case 7 '13
output = "M"
Case 8
output = "["
Case 9
output = "]"
End Select
Return output
End Function
Private Shared Function division(ByVal inputs As String, ByRef resto As String) As Integer
resto = ""
If inputs.Length > 1 Then
resto = inputs.Substring(1)
End If
Dim output As Integer = Integer.Parse(StrReverse(inputs).Substring(inputs.Length - 1))
Return output
End Function
Public Shared Function say(ByVal index As Integer, ByVal letter As String) As String
Dim output As String = ""
While Not index = 0
output = output & letter
index = index - 1
End While
Return output
End Function
Public Shared Function udctr(ByRef num As Integer) As Boolean
Dim und As Boolean = (num < 0)
If und Then
num = 0 - num
End If
Return und
End Function
End Class
Use the function hexRoman, like this example:
msgbox(Broman.hexRoman(50))
Public Class RomanNumber
Public Shared Function FromNumber(val As Byte) As String
Return GetNumberToRoman(val)
End Function
Public Shared Function FromNumber(val As SByte) As String
Return GetNumberToRoman(val)
End Function
Public Shared Function FromNumber(val As Int16) As String
Return GetNumberToRoman(val)
End Function
Public Shared Function FromNumber(val As Int32) As String
Return GetNumberToRoman(val)
End Function
Public Shared Function FromNumber(val As UInt16) As String
Return GetNumberToRoman(val)
End Function
Public Shared Function FromNumber(val As UInt32) As String
Return GetNumberToRoman(val)
End Function
Public Shared Function ToByte(val As String) As Byte
Return GetNumberFromRoman(val)
End Function
Public Shared Function ToSByte(val As String) As SByte
Return GetNumberFromRoman(val)
End Function
Public Shared Function ToInt16(val As String) As Int16
Return GetNumberFromRoman(val)
End Function
Public Shared Function ToInt32(val As String) As Int32
Return GetNumberFromRoman(val)
End Function
Public Shared Function ToUInt16(val As String) As UInt16
Return GetNumberFromRoman(val)
End Function
Public Shared Function ToUInt32(val As String) As UInt32
Return GetNumberFromRoman(val)
End Function
Private Shared Function GetNumberToRoman(val As Integer) As String
Dim v As String = ""
Do While val > 0
If val >= 1000 Then
v &= "M" : val -= 1000
ElseIf val >= 900 Then
v &= "CM" : val -= 900
ElseIf val >= 500 Then
v &= "D" : val -= 500
ElseIf val >= 400 Then
v &= "CD" : val -= 400
ElseIf val >= 100 Then
v &= "C" : val -= 100
ElseIf val >= 90 Then
v &= "XC" : val -= 90
ElseIf val >= 50 Then
v &= "L" : val -= 50
ElseIf val >= 40 Then
v &= "XL" : val -= 40
ElseIf val >= 10 Then
v &= "X" : val -= 10
ElseIf val >= 9 Then
v &= "IX" : val -= 9
ElseIf val >= 5 Then
v &= "V" : val -= 5
ElseIf val >= 4 Then
v &= "IV" : val -= 4
Else
v &= "I" : val -= 1
End If
Loop
Return v
End Function
Private Shared Function GetNumberFromRoman(val As String) As Object
Dim v As Integer = 0
If val.Contains("IV") Then v += 4 : val = val.Replace("IV", "")
If val.Contains("IX") Then v += 9 : val = val.Replace("IX", "")
If val.Contains("XL") Then v += 40 : val = val.Replace("XL", "")
If val.Contains("XC") Then v += 90 : val = val.Replace("XC", "")
If val.Contains("CD") Then v += 400 : val = val.Replace("CD", "")
If val.Contains("CM") Then v += 900 : val = val.Replace("CM", "")
For Each c As Char In val
If c = "I" Then v += 1
If c = "V" Then v += 5
If c = "X" Then v += 10
If c = "L" Then v += 50
If c = "C" Then v += 100
If c = "D" Then v += 500
If c = "M" Then v += 1000
Next
Return v
End Function
End Class

Performance loss in VB.net equivalent of light weight conversion from hex to byte

I have read through the answers here https://stackoverflow.com/a/14332574/44080
I've also tried to produce equivalent VB.net code:
Option Strict ON
Public Function ParseHex(hexString As String) As Byte()
If (hexString.Length And 1) <> 0 Then
Throw New ArgumentException("Input must have even number of characters")
End If
Dim length As Integer = hexString.Length \ 2
Dim ret(length - 1) As Byte
Dim i As Integer = 0
Dim j As Integer = 0
Do While i < length
Dim high As Integer = ParseNybble(hexString.Chars(j))
j += 1
Dim low As Integer = ParseNybble(hexString.Chars(j))
j += 1
ret(i) = CByte((high << 4) Or low)
i += 1
Loop
Return ret
End Function
Private Function ParseNybble(c As Char) As Integer
If c >= "0"C AndAlso c <= "9"C Then
Return c - "0"C
End If
c = ChrW(c And Not &H20)
If c >= "A"C AndAlso c <= "F"C Then
Return c - ("A"C - 10)
End If
Throw New ArgumentException("Invalid nybble: " & c)
End Function
Can we remove the compile errors in ParseNybble without introducing data conversions?
Return c - "0"c Operator '-' is not defined for types 'Char' and 'Char'
c = ChrW(c And Not &H20) Operator 'And' is not defined for types 'Char' and 'Integer'
As it stands, no.
However, you could change ParseNybble to take an integer and pass AscW(hexString.Chars(j)) to it, so that the data conversion takes place outside of ParseNybble.
This solution is much much faster than all the alternative i have tried. And it avoids any ParseNybble lookup.
Function hex2byte(s As String) As Byte()
Dim l = s.Length \ 2
Dim hi, lo As Integer
Dim b(l - 1) As Byte
For i = 0 To l - 1
hi = AscW(s(i + i))
lo = AscW(s(i + i + 1))
hi = (hi And 15) + ((hi And 64) >> 6) * 9
lo = (lo And 15) + ((lo And 64) >> 6) * 9
b(i) = CByte((hi << 4) Or lo)
Next
Return b
End Function

Barcode is hidden in reporting services

I have a report which carries a barcode , at the time of the Visual Studio preview it looks perfectly but when published to the server reporting services ( WEB ) does not show me the barcode as if hidden
This is the code I use within the report :
Public Shared Function Code39(ByVal stringText As String) As Byte()
Dim result As Byte() = Nothing
Try
result = GenerateImage("Code 3 de 9", StringToBarcode39String(stringText))
Catch ex As Exception
End Try
Return result
End Function
Public Shared Function Code128(ByVal stringText As String) As Byte()
Dim result As Byte() = Nothing
Try
result = GenerateImage("Code 128", StringToBarcode128String(stringText))
Catch ex As Exception
End Try
Return result
End Function
Public Shared Function GenerateImage(ByVal fontName As String, ByVal stringText As String) As Byte()
Dim oGraphics As System.Drawing.Graphics
Dim barcodeSize As System.Drawing.SizeF
Dim ms As System.IO.MemoryStream
Using font As New System.Drawing.Font(New System.Drawing.FontFamily(fontName), 36)
Using tmpBitmap As New System.Drawing.Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
oGraphics = System.Drawing.Graphics.FromImage(tmpBitmap)
oGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel
barcodeSize = oGraphics.MeasureString(stringText, font)
oGraphics.Dispose()
End Using
Using newBitmap As New System.Drawing.Bitmap(barcodeSize.Width, barcodeSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
oGraphics = System.Drawing.Graphics.FromImage(newBitmap)
oGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel
Using oSolidBrushWhite As New System.Drawing.SolidBrush(System.Drawing.Color.White)
Using oSolidBrushBlack As New System.Drawing.SolidBrush(System.Drawing.Color.Black)
oGraphics.FillRectangle(oSolidBrushWhite, New System.Drawing.Rectangle(0, 0, barcodeSize.Width, barcodeSize.Height))
oGraphics.DrawString(stringText, font, oSolidBrushBlack, 0, 0)
End Using
End Using
ms = New System.IO.MemoryStream()
newBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
End Using
End Using
Return ms.ToArray()
End Function
Public Shared Function StringToBarcode128String(ByVal value As String) As String
' Parameters : a string
' Return : a string which give the bar code when it is dispayed with CODE128.TTF font
' : an empty string if the supplied parameter is no good
Dim charPos As Integer, minCharPos As Integer
Dim currentChar As Integer, checksum As Integer
Dim isTableB As Boolean = True, isValid As Boolean = True
Dim returnValue As String = String.Empty
If value.Length > 0 Then
' Check for valid characters
For charCount As Integer = 0 To value.Length - 1
'currentChar = char.GetNumericValue(value, charPos);
currentChar = AscW(Char.Parse(value.Substring(charCount, 1)))
If Not (currentChar >= 32 AndAlso currentChar <= 126) Then
isValid = False
Exit For
End If
Next
' Barcode is full of ascii characters, we can now process it
If isValid Then
charPos = 0
While charPos < value.Length
If isTableB Then
' See if interesting to switch to table C
' yes for 4 digits at start or end, else if 6 digits
If charPos = 0 OrElse charPos + 4 = value.Length Then
minCharPos = 4
Else
minCharPos = 6
End If
minCharPos = IsNumber(value, charPos, minCharPos)
If minCharPos < 0 Then
' Choice table C
If charPos = 0 Then
' Starting with table C
' char.ConvertFromUtf32(210);
returnValue = (ChrW(210)).ToString()
Else
' Switch to table C
returnValue = returnValue & (ChrW(204)).ToString()
End If
isTableB = False
Else
If charPos = 0 Then
' Starting with table B
' char.ConvertFromUtf32(209);
returnValue = (ChrW(209)).ToString()
End If
End If
End If
If Not isTableB Then
' We are on table C, try to process 2 digits
minCharPos = 2
minCharPos = IsNumber(value, charPos, minCharPos)
If minCharPos < 0 Then
' OK for 2 digits, process it
currentChar = Integer.Parse(value.Substring(charPos, 2))
currentChar = IIf(currentChar < 95, currentChar + 32, currentChar + 105) ''
returnValue = returnValue & (ChrW(currentChar)).ToString()
charPos += 2
Else
' We haven't 2 digits, switch to table B
returnValue = returnValue & (ChrW(205)).ToString()
isTableB = True
End If
End If
If isTableB Then
' Process 1 digit with table B
returnValue = returnValue & value.Substring(charPos, 1)
charPos += 1
End If
End While
' Calculation of the checksum
checksum = 0
For [loop] As Integer = 0 To returnValue.Length - 1
currentChar = AscW(Char.Parse(returnValue.Substring([loop], 1)))
currentChar = IIf(currentChar < 127, currentChar - 32, currentChar - 105)
If [loop] = 0 Then
checksum = currentChar
Else
checksum = (checksum + ([loop] * currentChar)) Mod 103
End If
Next
' Calculation of the checksum ASCII code
checksum = IIf(checksum < 95, checksum + 32, checksum + 105)
' Add the checksum and the STOP
returnValue = returnValue & (ChrW(checksum)).ToString() & (ChrW(211)).ToString()
End If
End If
Return returnValue
End Function
Private Shared Function IsNumber(ByVal InputValue As String, ByVal CharPos As Integer, ByVal MinCharPos As Integer) As Integer
' if the MinCharPos characters from CharPos are numeric, then MinCharPos = -1
MinCharPos -= 1
If CharPos + MinCharPos < InputValue.Length Then
While MinCharPos >= 0
If AscW(Char.Parse(InputValue.Substring(CharPos + MinCharPos, 1))) < 48 OrElse AscW(Char.Parse(InputValue.Substring(CharPos + MinCharPos, 1))) > 57 Then
Exit While
End If
MinCharPos -= 1
End While
End If
Return MinCharPos
End Function
Public Shared Function StringToBarcode39String(ByVal value As String, Optional ByVal addChecksum As Boolean = False) As String
' Parameters : a string
' Return : a string which give the bar code when it is dispayed with CODE128.TTF font
' : an empty string if the supplied parameter is no good
Dim isValid As Boolean = True
Dim currentChar As Char
Dim returnValue As String = String.Empty
Dim checksum As Integer = 0
If value.Length > 0 Then
'Check for valid characters
For CharPos As Integer = 0 To value.Length - 1
currentChar = Char.Parse(value.Substring(CharPos, 1))
If Not ((currentChar >= "0"c AndAlso currentChar <= "9"c) OrElse (currentChar >= "A"c AndAlso currentChar <= "Z"c) OrElse currentChar = " "c OrElse currentChar = "-"c OrElse currentChar = "."c OrElse currentChar = "$"c OrElse currentChar = "/"c OrElse currentChar = "+"c OrElse currentChar = "%"c) Then
isValid = False
Exit For
End If
Next
If isValid Then
' Add start char
returnValue = "*"
' Add other chars, and calc checksum
For CharPos As Integer = 0 To value.Length - 1
currentChar = Char.Parse(value.Substring(CharPos, 1))
returnValue += currentChar.ToString()
If currentChar >= "0"c AndAlso currentChar <= "9"c Then
checksum = checksum + AscW(currentChar) - 48
ElseIf currentChar >= "A"c AndAlso currentChar <= "Z"c Then
checksum = checksum + AscW(currentChar) - 55
Else
Select Case currentChar
Case "-"c
checksum = checksum + AscW(currentChar) - 9
Exit Select
Case "."c
checksum = checksum + AscW(currentChar) - 9
Exit Select
Case "$"c
checksum = checksum + AscW(currentChar) + 3
Exit Select
Case "/"c
checksum = checksum + AscW(currentChar) - 7
Exit Select
Case "+"c
checksum = checksum + AscW(currentChar) - 2
Exit Select
Case "%"c
checksum = checksum + AscW(currentChar) + 5
Exit Select
Case " "c
checksum = checksum + AscW(currentChar) + 6
Exit Select
End Select
End If
Next
' Calculation of the checksum ASCII code
If addChecksum Then
checksum = checksum Mod 43
If checksum >= 0 AndAlso checksum <= 9 Then
returnValue += (ChrW(checksum + 48)).ToString()
ElseIf checksum >= 10 AndAlso checksum <= 35 Then
returnValue += (ChrW(checksum + 55)).ToString()
Else
Select Case checksum
Case 36
returnValue += "-"
Exit Select
Case 37
returnValue += "."
Exit Select
Case 38
returnValue += " "
Exit Select
Case 39
returnValue += "$"
Exit Select
Case 40
returnValue += "/"
Exit Select
Case 41
returnValue += "+"
Exit Select
Case 42
returnValue += "%"
Exit Select
End Select
End If
End If
' Add stop char
returnValue += "*"
End If
End If
Return returnValue
End Function
Do I use assemblies , And the barcode image is kind
Could it be that on the server the barcode font is missing?

Developing Fibonacci Series in VB

I am trying to write a code for Fibonacci series in VB, but some of the values in my series are incorrect. Can somebody help me with the code?
Below is what I have so far.
Private Function FibNumber(number As Integer) As Integer
If (number > 2) Then
FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
Else
FibNumber = 1
End If
End Function
Private Sub command1_click()
Dim x As Integer
x = Text1.Text
Call FibNumber(number)
End Sub
Well, I did a quick search and I came up with the following in the first couple of results:
Private Function FibNumber(number As Integer) As Integer
If (number > 2) Then
FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
Else
FibNumber = 1
End If
End Function
I know this is way old, but I think the issue could be with how compgeek is calling the function.
Instead of:
Call FibNumber(number)
It should be:
Call FibNumber(x)
My solution:
Private Function FibNumber(number As Integer) As Integer
If (number > 2) Then
FibNumber = (FibNumber(number - 2) + FibNumber(number - 1))
Else
FibNumber = 1
End If
End Function
Private Sub command1_click()
Dim x As Integer
x = Text1.Text
Call FibNumber(number)
End Sub
It's a Java function, and believe me; Fibonacci wont get much more faster or complex than
this particular version. It is optimized to operate at about 100 times faster than the original recursive one.
Tip: You might need to change maxN to extend parameter length!
For example if you want to input numbers between 0 and 199, you must increase the maxN to 200
static final int maxN = 72;
static long knownF[] = new long[maxN];
static long F(int i) {
if (knownF[i] != 0) {
return knownF[i];
}
long t = i;
if (i < 0) {
return 0;
}
if (i > 1) {
t = F(i - 1) + F(i - 2);
}
return knownF[i] = t;
}
Module Module1
Sub Main()
Console.WriteLine("The Fibonacci Series")
Console.WriteLine("Enter how many elements-")
Dim n As Integer = Console.ReadLine
If (n = 1) Then
Dim a As Integer = 1
Console.WriteLine("{0}", a)
Else
Dim a As Integer = 1
Dim b As Integer = 2
Console.WriteLine("{0}", a)
Console.WriteLine("{0}", b)
Dim i As Integer = 1
While (i < n - 1)
Dim c As Integer = a + b
Console.WriteLine(" {0}", c)
a = b
b = c
i = i + 1
End While
End If
Console.ReadKey()
End Sub
End Module