Cary Bondoc
Cary Bondoc

Reputation: 2988

Convert hex to binary while retaining their places

I have this code that converts 7 to binary.

Dim s As String = "7"
Dim i As Integer = Convert.ToInt32(s, 16)
Dim s2 As String = Convert.ToString(i, 2)
Console.WriteLine(s2) 'result is 111

My problem is this, I want to apply the 8 bit binary so I can easily substring the result.

Instead of the result that is 111, I would like to make it 0111.

Examples:

Binary / Hex

 1. F = 1111
 2. 7 = 0111
 3. 1 = 0001

Upvotes: 0

Views: 677

Answers (1)

ɐsɹǝʌ ǝɔıʌ
ɐsɹǝʌ ǝɔıʌ

Reputation: 4512

You can pad the result with starting zero by using PadLeft.

s2.PadLeft(4, "0")

Upvotes: 1

Related Questions