In this web i see that all answer about thins like converting decimal number to binary
its refers number without point in the number(int)...
i want to know how to convert the decimal number with point like "332.434" to binary in c#
例如,我看到:
using System;
namespace _01.Decimal_to_Binary
{
class DecimalToBinary
{
static void Main(string[] args)
{
Console.Write("Decimal: ");
int decimalNumber = int.Parse(Console.ReadLine());
int remainder;
string result = string.Empty;
while (decimalNumber > 0)
{
remainder = decimalNumber % 2;
decimalNumber /= 2;
result = remainder.ToString() + result;
}
Console.WriteLine("Binary: {0}",result);
}
}
}
例子引用从无点转换而来
谢谢
答案 0 :(得分:1)
只需使用BitConverter获取字节然后循环,然后将它们转换为字符串并将当前字符串附加到前一个字符串。
byte[] byteArray = BitConverter.GetBytes(MyDouble);
string ByteString = System.String.Empty;
for (int i = 0; i < byteArray.Length; i++)
ByteString = Convert.ToString(byteArray[i], 2).PadLeft(8, '0');
您可能需要做一些修补以获得正确顺序的位,但我认为BysteString将在左侧具有高位。这是ToString方法http://msdn.microsoft.com/en-us/library/8s62fh68.aspx
的MSDN页面答案 1 :(得分:-1)
您不能简单地将非整数转换为二进制格式。例如。对于3.145926,计算机保留一个符号(+/-),一个数字本身,但始终为零(0.3141596)和尾数(E-1)。所以你需要保留所有3个部分。在维基百科http://en.wikipedia.org/wiki/Floating_point#Representable_numbers.2C_conversion_and_rounding
中阅读更多内容