i want to use Regex.IsMatch to find TB, GB, MB in VB.net Visual Basic - vb.net

I have a textbox which i need to validate for the below entries and also need to replace
"3 GB" valid input
"3.2 GB" valid input
"3.2GB" valid input >> then replace as "3.2 GB"
"3.2" invalid input, ask for follow correct format MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
"VGGGB" invalid input, ask for follow correct format MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Sub Main()
Dim input = Console.ReadLine().ToUpper()
Dim nInput, value
Dim ChkDecimal As Double
If input IsNot "" Then
If input.EndsWith("TB") Then
nInput = input.Replace("TB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1048576 + 1)
ChkDecimal = FormatNumber(CDbl(value / 1048576), 2) Mod 1 ' check the number has a valid Decimal value
If ChkDecimal = 0 Then
Console.WriteLine(FormatNumber(CDbl(value / 1048576), 0) & " TB")
Else
Console.WriteLine(FormatNumber(CDbl(value / 1048576), 2) & " TB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
ElseIf (input.EndsWith("GB")) Then
nInput = input.Replace("GB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1024)
ChkDecimal = FormatNumber(CDbl(value / 1024), 2) Mod 1 ' check the number has a valid Decimal value
If ChkDecimal = 0 Then
Console.WriteLine(FormatNumber(CDbl(value / 1024), 0) & " GB")
Else
Console.WriteLine(FormatNumber(CDbl(value / 1024), 2) & " GB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
ElseIf input.EndsWith("MB") = True Then
nInput = input.Replace("MB", "")
If nInput IsNot vbNullString And IsNumeric(nInput) Then
value = Convert.ToDouble(nInput)
value = CDbl(value * 1)
Console.WriteLine(FormatNumber(CDbl(value * 1), 0) & " MB")
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
Else
Console.WriteLine("Invalid format!! should like: 99.99 MB/GB/TB")
End If
Else
Console.WriteLine("Capacity input Format: 99.99 MB/GB/TB")
End If
End Sub

I wouldn't use a regular-expression for this, because there's a much simpler (and more robust!) approach described below.
If you do use a regular-expression, you'll need to add all of the unit names to the expression, which is painful. Regular-expressions are not well-suited to accepting a large list of possible literal inputs.
Using a regular-expression would also mean the input would not be culture-aware, which is bad for usability (as many places around the world swap the , and . glyphs in numbers) - and you really don't want to handle things like digit-grouping, etc.
Instead, first extract and validate the unit name, then parse the numeric value using Decimal.TryParse
Like so (using C# because it's 2am here and I'm not getting paid to write this answer):
void Example()
{
String textBoxValue = "3 GB";
if( TryParseBinaryDataQuantity( textBoxValue, out Int64 valueBytes ) )
{
MessageBox.Show( "Visual Basic is dead." );
}
else
{
MessageBox.Show( "Input is not a valid binary data quantity." );
}
}
public static Boolean TryParseBinaryDataQuantity( String input, out Int64 valueBytes )
{
input = ( input ?? "" ).Trim();
if( input.Length < 3 ) // input is too short to be meaningful.
{
valueBytes = default;
return false;
}
// Extract the unit-name by taking the last 3 characters of the input string and trimming any whitespace (this isn't the most robust or correct approach, but I'm feeling lazy):
String unitName = input.Substring( startIndex: input.Length - 3 );
// Validate the unit-name and get the bytes multiplier:
if( !TryParseBinaryDataUnit( unitName, out Int64 multiplier ) )
{
valueBytes = default;
return false;
}
// Consider repeating the above but for the last 2 characters of the string in order to match input like "3GB" instead of "3GiB" and "3 GB" and "3 GiB".
// Parse and multiply:
String numberPart = input.Substring( startIndex: 0, length: input.Length - 3 );
if( Decimal.TryParse( numberPart, NumberStyles.Any, CultureInfo.CurrentCulture, out Decimal quantity )
{
Decimal bytesValue = quantity * multiplier;
// Fail if the bytesValue is non-integral or negative:
if( bytesValue != Math.Floor( bytesValue ) || bytesValue < 0 )
{
valueBytes = default;
return false;
}
return (Int64)bytesValue;
}
}
private static Boolean TryParseBinaryDataUnit( String unitName, out Int64 equivalentBytes )
{
if( "GB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024 * 1024; // or 1000 * 1000 * 1000 depending on if you're differentiating between GiB and GB.
return true;
}
else if( "GiB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024 * 1024;
return true;
}
else if( "MiB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024;
return true;
}
else if( "MB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024 * 1024;
return true;
}
else if( "KB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024;
return true;
}
else if( "KB".Equals( unitName, StringComparison.CurrentCultureCaseInsensitive ) )
{
equivalentBytes = 1024;
return true;
}
else
{
equivalentBytes = default;
return false;
}
}

I will recommend you to use proper library to parse the given input. I have used one in past for doing this (https://github.com/omar/ByteSize)
Here is quick example of how you can do this. I know there must be better way to do this but this would do the job =)
var input = Console.ReadLine();
input = input.ToLower();
var reg = Regex.Match(input, "([\\d\\.]+)");
if (reg.Success && double.TryParse(reg.Groups[1].Value, out double rawSize))
{
if (input.EndsWith("tb"))
Console.WriteLine(ByteSize.FromTeraBytes(rawSize));
else if (input.EndsWith("gb"))
Console.WriteLine(ByteSize.FromGigaBytes(rawSize));
else if (input.EndsWith("mb"))
Console.WriteLine(ByteSize.FromMegaBytes(rawSize));
else if (input.EndsWith("kb"))
Console.WriteLine(ByteSize.FromKiloBytes(rawSize));
}
Input> 1234.56mb
Output> 1.23 GB

You can try my method as following:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'1.3 GB
'1.3gb
'1gb
Console.WriteLine("Pleasen input your entry:")
Dim str As String = TextBox1.Text
Dim str1 As String = str.Substring(str.Length - 2, 2)
If str1.ToUpper = "TB" Or str1.ToUpper = "GB" Or str1.ToUpper = "MB" Then
Dim str2 As String = str.Remove(str.Length - 2)
Dim str3 As String = str.Substring(str2.Length - 1, 1)
If str3 = " " Then
Dim str4 As String = str.Remove(str.Length - 3)
If Regex.IsMatch(str4, "^\d*[.]?\d*$") Then
MsgBox("valid input")
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
Else
If Regex.IsMatch(str2, "^\d*[.]?\d*$") Then
TextBox1.Text = str.Insert(str.Length - 2, " ")
MsgBox("valid input")
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
End If
Else
MsgBox("follow the format like: 1 TB or 1.1 TB, 1 GB, 10 MB")
Return
End If
End Sub
End Class

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

Any way to convert from Double to Hex in vb?

I want to add a text box where a user can input a number. No matter how large or small the number, it needs to be stored as a double. Then with a click button, the hex equivalent will be displayed in a second text box. Bonus points if you can show me how to take the 16 byte hex and change it to 4 variables with 4 bytes each.
For example, user enters 1234.56 in textbox1. Clicks button 1, and textbox2 displays the hex equivilent "40934A3D70A3D70A" Then take that string, and extract to 4 different 4-byte strings so str1=1093, str2=4A3D, str3=70a3, str4=d70A.
Are you looking for BitConverter? C# implementation:
double source = 1234.56;
// 40934A3D70A3D70A
string result = string.Concat(BitConverter
.GetBytes(source)
.Reverse()
.Select(b => b.ToString("X2")));
Having got result, extract its parts with Substring:
string str1 = result.Substring(0, 4);
string str2 = result.Substring(4, 4);
string str3 = result.Substring(8, 4);
string str4 = result.Substring(12, 4);
If you are looking for a C# implementation, try this:
static void Main(string[] args)
{
var number = 1234.56;
string hex = DoubleToHex(number);
string part1 = hex.Substring(0, 4);
string part2 = hex.Substring(4, 4);
string part3 = hex.Substring(8, 4);
string part4 = hex.Substring(12, 4);
}
internal static string DoubleToHex(double value)
{
var b = BitConverter.GetBytes(value).Reverse();
string result = string.Join(string.Empty, b.Select(i => i.ToString("X2")).ToArray());
return result;
}
This is the most efficient answer you're going to get:
unsafe static void Main()
{
var value = 1234.56;
var pLong = (long*)&value;
var fullString = (*pLong).ToString("X");
var pShort = (short*)pLong;
short value0 = *pShort, value1 = *(pShort + 1), value2 = *(pShort + 2),
value3 = *(pShort + 3);
string s0 = value0.ToString("X"), s1 = value1.ToString("X"), s2 = value2.ToString("X"),
s3 = value3.ToString("X");
Debug.Print(fullString);
Debug.Print(s0);
Debug.Print(s1);
Debug.Print(s2);
Debug.Print(s3);
}
Output:
40934A3D70A3D70A
D70A
70A3
4A3D
4093
Translation of Dmitry Bychenko answer to VB.NET:
Imports SplitValue = System.Tuple(Of String, String, String, String)
Module Module1
Function DoubleToByteArray(ByVal AValue As Double) As Byte()
Return BitConverter.GetBytes(AValue).Reverse().ToArray()
End Function
Function SplitByteArray(ByRef AValue As Byte()) As SplitValue
Dim StringValue As String = String.Join("", From AByte In AValue Select AByte.ToString("X2"))
Return New SplitValue(StringValue.Substring(0, 4), StringValue.Substring(4, 4), StringValue.Substring(8, 4), StringValue.Substring(12, 4))
End Function
Sub Main()
Dim Result As SplitValue
Result = SplitByteArray(DoubleToByteArray(1234.56))
Console.WriteLine(Result)
Console.ReadLine()
End Sub
End Module
Output:
(4093, 4A3D, 70A3, D70A)
try it: DoubleToHex
//dashseparator 0 /2/4
public string DoubleToHex(double d, bool reverse = false, int dashSeparator = 0)
{
byte[] bytes = BitConverter.GetBytes(d);
if (reverse) bytes = bytes.Reverse().ToArray();
var hex = BitConverter.ToString(bytes);
var hex4 = "";
if (dashSeparator == 2) return hex;
if (dashSeparator == 4)
{
hex = hex.Replace("-", "");
hex = Regex.Replace(hex, ".{4}", "$0-").TrimEnd('-');
return hex;
}
return hex.Replace("-", "");
}
sample Output:
Double: 1234.56
Hex: 0AD7A3703D4A9340
Hex in Reverse order: 40934A3D70A3D70A
Hex in Reverse order separate by 2 digits: 40-93-4A-3D-70-A3-D7-0A
Hex in Reverse order separate by 4 digits: 4093-4A3D-70A3-D70A
you can :
-control the generated Hex to be displayed in order/ reverse order.
-Add dash separator by 0 (no separator) / 2 /4 digits
Edit:
Vb.Net Version
Converting Code to Vb.Net
'dashseparator 0 /2/4
Public Function DoubleToHex(d As Double, Optional reverse As Boolean = False, Optional dashseparator As Integer = 0) As String
Dim bytes As Byte() = BitConverter.GetBytes(d)
If reverse Then
Array.Reverse(bytes)
End If
Dim hex = BitConverter.ToString(bytes)
Dim hex4 = ""
If dashseparator = 2 Then
Return hex
End If
If dashseparator = 4 Then
hex = hex.Replace("-", "")
hex = Regex.Replace(hex, ".{4}", "$0-").TrimEnd("-"C)
Return hex
End If
Return hex.Replace("-", "")
End Function

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

How to do this in Visual basic?

How to do the "a++" and "b++" in Visual basic?
What is the another codes for there in Vb?
The names there are just example.
int a = 0;
int b = 0;
{
if (ans1.Text == "James")
{
a++;
}
else
{
b++;
}
if (ans2.Text == "Ryan")
{
a++;
}
else
{
b++;
}
if (ans3.Text == "Mac")
{
a++;
}
else
{
b++;
}
t1.Text = a.ToString();
t2.Text = b.ToString();
}
Like this:
a += 1
b += 1
(...)
Like this
DIM a as integer = 0
DIM b as integer = 0
If ans1.Text = "James" Then
a += 1
Else
b += 1
End If
If ans2.Text = "Ryan" Then
a += 1
Else
b += 1
End If
If ans3.Text = "Mac" Then
a += 1
Else
b += 1
End If
t1.Text = a.ToString()
t2.Text = b.ToString()
Your question has already been answered but I think it would be useful to see how you could simplify your code:
Dim correctAnswers As Integer = 0
Dim totalQuestions As Integer = 3'you need to modify this is you add more questions
'increment the number of correct answers for each one we find
correctAnswers += If(ans1.text = "James", 1, 0)
correctAnswers += If(ans2.text = "Ryan", 1, 0)
correctAnswers += If(ans3.text = "Mac", 1, 0)
'show the number of correct and incorrect answers
t1.Text = correctAnswers.ToString()
t2.Text = (totalQuestions - correctAnswers).ToString() 'show the number of incorrect questions
Neither the postfix nor prefix ++ are defined in Visual Basic.
Your only realistic option is to use a = a + 1 (or, in later BASICs, a += 1) instead (note the lack of a ; for a statement terminator). But note that this will not evaluate to the previous value of a and the entire construct is not an expression in the C / C++ sense. You could build a function to mimic a++ but that would be too obfuscating.

Splitting a String into Pairs

How would I go on splitting a string into pairs of letter in VB?
for example: abcdefgh
split into: ab cd ef gh
I'll throw my hat in the ring:
Dim test As String = "abcdefgh"
Dim results As New List(Of String)
For i As Integer = 0 To test.Length - 1 Step 2
If i + 1 < test.Length Then
results.Add(test.Substring(i, 2))
Else
results.Add(test.Substring(i))
End If
Next
MessageBox.Show(String.Join(" ", results.ToArray))
The following allows for odd length strings. If the string is zero-length, I'm not sure what you'd want to do, you'll want to address that case.
Dim src As String = "abcdef"
Dim size As Integer
If src.Length > 0 Then
If src.Length Mod 2 = 0 Then
size = (src.Length / 2) - 1
Else
size = ((src.Length + 1) / 2) - 1
End If
Dim result(size) As String
For i = 0 To src.Length - 1 Step 2
If i = src.Length - 1 Then
result(i / 2) = src.Substring(i, 1)
Else
result(i / 2) = src.Substring(i, 2)
End If
Next
End If
In C# you would do like this:
Dictionary<String, String> Split(String input)
{
if (input.Count % 2 == 0)
{
Dictionary<string, string> Pairs = new Dictionary( );
for (int L = 0, R = 1; L < input.Count && R <= input.Count; ++L, ++R)
{
Char
Left = input[L],
Right = input[R];
Pairs.Add(
Left.ToString(),
Right.ToString());
}
}
else
{
throw new NotEvenException( );
}
return Pairs( );
}
void Main()
{
var Pairs = Split("ABCDEFGH");
foreach(string Key in Split("ABCDEFGH"))
{
Console.Write("{0}{1}\n", Key, Pairs[Key]);
}
}
/*
Output:
AB
CD
EF
GH
*/
Now, I know what you think: This isn't what I want! But I say: It is actually, at least partly.
Since I presume you're working in VB.net, the basic structure of what you want performed is outlined in the short snippet above.
For example: The method Count (of the object String) exists in both C# and in VB.
Hope it helps a bit at least!