68114

Binary Converter to Decimal with .NET

I'm started to get the hang of some programming basics but I'm still very new and inexperienced. I am having trouble with a new program I am coding.

I want to have a program in which an 8-bit binary number is put in a textbox, a button is pressed, and the decimal value of the binary number is shown.

Below is the code i have tried:

Public Class Form1 Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click Dim N As Integer N = Convert.ToDouble(tbxBin.Text) N = N Mod 2 N = N \ 2 lblAns.Text = Convert.ToString(N) End Sub End Class

Sadly, when I run the program I only get a decimal number of 0 no matter what binary code I put in. I'm very confused because I was told the use Mod class. When I look online for a solution to my problem, I see techniques and various coding processes I've never seen before.

Apparently with my code, I have to repeat what I typed for as many bits as the user is typing in, however, I'm confused as to how I go about that. Do I Dim new variables?

Any and all help is greatly appreciated. Thank you.

Answer1:

Edit: See below for going the other way!! I misread.

Binary to Decimal:

Public Function ConvertFromBinary(ByVal input As String) As Integer Dim ret As Integer = 0 Dim splitInput As Char() = input.ToCharArray Dim modifier As Integer = 1 For i As Integer = splitInput.Length - 1 To 0 Step -1 Dim thisChar As Integer = Val(splitInput(i)) If thisChar = 1 Then ret += thisChar * modifier End If modifier *= 2 Next Return ret End Function

...And back again:

Easy answer?

Convert.ToString(input, 2)

Since that's no fun, however:

Public Function ConvertToBinary(ByVal input As Integer) As String Dim ret As String = "" While input > 0 ret &= input Mod 2 input = input \ 2 End While Return StrReverse(ret) End Function

Answer2:

The hard way

Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click Dim pwrOf2 As Integer = 0 Dim ans As Long = 0L 'first check if the user input a number If Long.TryParse(tbxBin.Text, Nothing) Then 'then look at each char in reverse For Each n As Char In tbxBin.Text.Reverse Select Case n Case Is = "0"c Case Is = "1"c ans += 1L << pwrOf2 Case Else 'error - input not in binary, only 1's and 0's Stop End Select pwrOf2 += 1 Next lblAns.Text = ans.ToString("n0") Else 'not a number End If End Sub

Answer3:

just a suggestion, start by making a function like this:

Public Function Bin_To_Dec(ByVal Bin As String) Dim dec As Double = Nothing Dim length As Integer = Len(Bin) Dim temp As Integer = Nothing Dim x As Integer = Nothing For x = 1 To length temp = Val(Mid(Bin, length, 1)) length = length - 1 If temp <> "0" Then dec += (2 ^ (x - 1)) End If Next Return dec End Function

then call it with this:

txtZ.Text = Bin_To_Dec(txtX.Text)

Answer4:

first convert to an array of integer then convert that to binary see the code below

public static Byte[] SerializeDecimal(Decimal decimalValue) { Int32[] arraydDecimalToInt32 = Decimal.GetBits(decimalValue); ; Byte[] byteData = new byte[sizeof(Int32) * arraydDecimalToInt32.Length]; for (Int32 index2 = 0; index2 < arraydDecimalToInt32.Length; index2++) { Array.Copy(BitConverter.GetBytes(arraydDecimalToInt32[index2]), 0, byteData, index2 * sizeof(Int32), sizeof(Int32)); } return byteData; } public static Decimal DeserializeDecimal( Byte[] data) { Int32[] parts = new Int32[4]; for (Int32 index = 0; index < 4; index++) { parts[index] = BitConverter.ToInt32(data, index*4); } bool sign = (parts[3] & 0x80000000) != 0; byte scale = (byte)((parts[3] >> 16) & 0x7F); return new Decimal(parts[0], parts[1], parts[2], sign, scale); //See http://msdn.microsoft.com/en-us/library/system.decimal.getbits(v=vs.110).aspx }

Answer5:

Sub Main() Dim binarystring As String Dim bitvalue As Integer Dim denaryvalue As Integer = 0 Dim bit As String Dim i As Integer Console.WriteLine("Enter the binary string") binarystring = Console.ReadLine Dim lenstring As Integer = Len(binarystring) For i = 1 To Len(binarystring) bit = Mid(binarystring, i, 1) bitvalue = Int(bit) denaryvalue = 2 ^ (lenstring - i) * bitvalue + denaryvalue Next Console.WriteLine(denaryvalue) Console.ReadLine() End Sub

Recommend

  • Removing duplicates from 2d array in Javascript
  • How to add a hyperlink in a Google Docs using a Google Script
  • Is there any advantage to naming function declarations?
  • Boxing..do I get it right? [duplicate]
  • Installing MEAN Stack: npm -v module.js: 338 throw err; Error: Cannot find module './cache/cach
  • How to make a npm command, that executes two commands in the console (one after another)?
  • In VIm, how to remove all lines that are duplicate somewhere?
  • IE readonly textarea problem
  • Adding independent aspx/asmx pages into DotNetNuke
  • Backward compatibility of Python 3.5 for external modules
  • xtable - background colour of added rows
  • Hibernate to update table schema
  • Find group of records that match multiple values
  • DIV instruction jumping to random location?
  • How to detect interior vertices in groups of 2d polygons? (E.g. ZIP Codes to determine a territory)
  • Center align outputs in ipython notebook
  • C# program and C++ DLL compiled for 32-bit system crash on 64-bit system
  • Convert Type Decimal to Hex (string) in .NET 3.5
  • Z3: Convert between FP and BitVector?
  • Abort upload large uploads after reading headers
  • Custom Tabgroup Appcelerator
  • PHPUnit_Framework_TestCase class is not available. Fix… - Makegood , Eclipse
  • Projection media query: browser support and workarounds?
  • Different response to non-authenticated users and AJAX calls
  • Fetching methods from BroadcastReceiver to update UI
  • How to extract text from Word files using C#?
  • Deserializing XML into class C#
  • Symfony2: How to get request parameter
  • Statically linking a C++ library to a C# process using CLI or any other way
  • How do you troubleshoot character encoding problems?
  • GridView Sorting works once only
  • Buffer size for converting unsigned long to string
  • WPF Applying a trigger on binding failure
  • Authorize attributes not working in MVC 4
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Does armcc optimizes non-volatile variables with -O0?
  • Busy indicator not showing up in wpf window [duplicate]
  • Conditional In-Line CSS for IE and Others?
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF