Click here to Skip to main content
16,007,111 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private string hex2binary(string hexvalue)
{
  string binaryval = "";
  binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
  return binaryval;
}


This code convert hex to binary properly. But i want out put in 8 digit and this code not give.
For ex:
If my hex is 2 then i want 0000 0010 and instead of this my code give only 10.
so help me.
Posted
Updated 22-Nov-11 2:35am
v2

use the below line

Convert.ToString(Convert.ToInt32(hexvalue, 16), 2).PadLeft(8,'0')
 
Share this answer
 
use the PadLeft function of the string to pad zeroes to the left

Ref:http://msdn.microsoft.com/en-us/library/system.string.padleft.aspx[^]

C#
private string hex2binary(string hexvalue)
{
  string binaryval = "";
  binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
  binaryval = binaryval.PadLeft(8,'0');
  return binaryval;
}
 
Share this answer
 
The String.PadLeft method creates a new string that is right-aligned so that its last character is a specified number of spaces from the first index of the string. White spaces are inserted if you do not use an override that allows you to specify your own custom padding character.

For example you would use it like this:

C#
protected string hex2binary(string hexvalue, int  iPaddingLength)
{
    string binaryval = "";
    binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
    binaryval = binaryval.PadLeft(iPaddingLength, '0');
    return binaryval;
}
 
Share this answer
 
Hi,


You need to use Number Format Method to specify your string number pattern.
look at the example on this link :




Number Formatting[^]


Regards
 
Share this answer
 
v2
string binaryval = "";
string bi = "";
binaryval = Convert.ToString(Convert.ToInt32(textBox1.Text, 16), 2);
if (binaryval.Length < 8)
{
for (int i = binaryval.Length; i < 8; i++)
{
bi = '0' + binaryval;
binaryval = bi;
}
textBox2.Text = bi;
}
 
Share this answer
 
You may simply add the required 0s:
C#
private string hex2binary(string hexvalue)
{
  string binaryval = "";
  binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
  binaryval = binaryval.PadLeft(8, '0');
  return binaryval.Insert(4, " ");	
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900