想要将十六进制转换为二进制 [英] want to convert hex in to binary

查看:90
本文介绍了想要将十六进制转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private string hex2binary(string hexvalue)
{
  string binaryval = "";
  binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
  return binaryval;
}



此代码将十六进制正确转换为二进制.但我想输入8位数字,而此代码不给出.
例如:
如果我的十六进制是2,那么我要0000 0010,而我的代码只给出10.
因此,请帮助我.



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.

推荐答案

使用下面的行

use the below line

Convert.ToString(Convert.ToInt32(hexvalue, 16), 2).PadLeft(8,''0'')


使用字符串的PadLeft函数将零填充到左侧

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

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[^]

private string hex2binary(string hexvalue)
{
  string binaryval = "";
  binaryval = Convert.ToString(Convert.ToInt32(hexvalue, 16), 2);
  binaryval = binaryval.PadLeft(8,'0');
  return binaryval;
}


String.PadLeft方法创建一个右对齐的新字符串,以使它的最后一个字符与该字符串的第一个索引相距指定的空格数.如果不使用允许您指定自己的自定义填充字符的替代,则会插入空格.

例如,您可以这样使用它:

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:

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


这篇关于想要将十六进制转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆