Sign up to the jQuery Grid Subscription list.
Showing posts with label binary. Show all posts
Showing posts with label binary. Show all posts

convert binary to octal ,hexadecimal and decimal numbers

This is the second part of the previous question.

The response by Martin Xie - MSFT:

By means of Convert class, you can first convert Binary to Decimal Intger, and then convert Decimal to Octal and Hexadecimal string.

Imports Microsoft.VisualBasic

Imports System

Imports System.Collections.Generic

Imports System.Text



Friend Class Program

Shared Sub Main(ByVal args As String())



Dim bin As String = "1000001" 'Binary string



Dim decimalValue As Integer

Dim hexValue As String

Dim OctalValue As String



decimalValue = Convert.ToInt32(bin, 2) 'First convert Binary to Decimal Intger

Console.WriteLine("Decimal:" & decimalValue)



OctalValue = Oct(decimalValue) 'Convert Decimal to Octal string

Console.WriteLine("Octal:" & OctalValue)



hexValue = Hex(decimalValue) 'Convert Decimal to Hexadecimal string

Console.WriteLine("Hexadecimal:" & hexValue)



Console.Read()



End Sub



End Class



The output will be:

Decimal: 65

Octal: 101

Hexadecimal: 41

Convert ASCII Code/Character to Binary Number

Original post by rattlesnake316 at http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2159243&SiteID=1

The question:

Hello! Hope someone could help me on converting ASCII characters to Binary
Also,hope you know how to convert Boolean Number to Octal or Hexadecimal or Decimal number.
Thanks in advance!

The accepted answer by Martin Xie - MSFT :

Hi rattlesnake,

ASCII can only represent character codes between 0 and 127.

About converting ASCII characters to Binary,

e.g. convert AscII value 66 of character B to Binary like this:


Imports Microsoft.VisualBasic

Imports System

Imports System.Collections.Generic

Imports System.Text



Friend Class Program

Shared Sub Main(ByVal args As String())



Dim myChar As Char = "B"c

Dim j As Integer = 0

Dim ascii As Integer = System.Convert.ToInt32(myChar)

Console.WriteLine("ASCII:" & ascii)

Dim binTempResult As String = ""

Do While ascii > 0

j = ascii Mod 2

binTempResult &= j.ToString()

ascii = ascii \ 2

Loop



'reverse output

Dim arr As Char() = binTempResult.ToCharArray()

Array.Reverse(arr)

Dim binResult As String = New String(arr)

System.Console.Write(binResult)

Console.Read()



End Sub



End Class


The output will be:

ASCII:66

1000010