Giả sử sau đây là phao của chúng tôi -
float n = 50.5f;
Lấy một chuỗi trống để hiển thị giá trị nhị phân và lặp lại cho đến khi giá trị của biến float lớn hơn 1 -
string a = "";
while (n >= 1) {
a = (n % 2) + a;
n = n / 2;
} Hãy để chúng tôi xem ví dụ hoàn chỉnh -
Ví dụ
using System;
using System.IO;
using System.CodeDom.Compiler;
namespace Program {
class Demo {
static void Main(string[] args) {
// float to binary
Console.WriteLine("float to binary = ");
float n = 50.5f;
string a = "";
while (n >= 1) {
a = (n % 2) + a;
n = n / 2;
}
Console.Write(a);
}
}
} Đầu ra
float to binary = 1.5781251.156250.31250.6251.250.5