How to convert float/double/ulong into binary/otcal/hex string??
-
Thursday, May 15, 2008 7:19 AMHi, all.
As I known, i can conver int into binary/otcal/hex string by using
Convert.ToString( int_var, 2/8/16);
But how can i convert float/double/ulong into binary/otcal/hex string????
All Replies
-
Thursday, May 15, 2008 8:04 AM
You should first convert the value to a byte array and then construct the string from that array:
string s = String.Empty;
// value is the value you want to convert to a string (double, long, int, ...)
foreach (byte b in BitConverter.GetBytes(value))
{
s += Convert.ToString(b,16).PadLeft(2,'0'); // for hex. For binary, use 2 and 8. For octal, use 8 and 3
} -
Thursday, May 15, 2008 8:23 AMThank you, It works.....
-
Wednesday, February 22, 2012 12:16 PM
You should first convert the value to a byte array and then construct the string from that array:
支持 ulong 吗?
string s = String.Empty;
// value is the value you want to convert to a string (double, long, int, ...)
foreach (byte b in BitConverter.GetBytes(value))
{
s += Convert.ToString(b,16).PadLeft(2,'0'); // for hex. For binary, use 2 and 8. For octal, use 8 and 3
}
-
Friday, February 24, 2012 5:28 AM
You should first convert the value to a byte array and then construct the string from that array:
支持 ulong 吗?
string s = String.Empty;
// value is the value you want to convert to a string (double, long, int, ...)
foreach (byte b in BitConverter.GetBytes(value))
{
s += Convert.ToString(b,16).PadLeft(2,'0'); // for hex. For binary, use 2 and 8. For octal, use 8 and 3
}
乱马客,钱仔,你们好:)
首先非常感谢乱马客你提供的答案,给我也很多启发;我这里补充一下,因为BitConverter转化的GetBytes是低位在前,高位在后;因此按照此连接读取有些不太直观(直观的读法应该是:从右到左,2的0次方,……2的N次方)。下面给出一个改进程序:
ulong unum = 10010;
byte[] bytes = BitConverter.GetBytes(unum);
string s = "";
foreach (var item in bytes)
{
s = Convert.ToString(item, 2).PadLeft(8,'0') + s; //可以把2改成8或者16,那么基数就是8和16了。
}
Console.WriteLine(s);


