ในการแปลงลอยเป็นไบนารี รหัส Java มีดังต่อไปนี้ -
ตัวอย่าง
import java.io.*;
public class Demo {
static void decimal_to_bin(int n){
int[] bin_num = new int[50];
int i = 0;
while (n > 0){
bin_num[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--)
System.out.print(bin_num[j]);
}
public static void main (String[] args){
int n = 89;
System.out.println("The conversion from floating to binary is ");
decimal_to_bin(n);
}
} ผลลัพธ์
The conversion from floating to binary is 1011001
คลาสที่ชื่อ Demo มีฟังก์ชันชื่อ 'decimal_to_bin' ซึ่งแปลงเลขทศนิยมที่กำหนดให้เป็นเลขฐานสองโดยการวนซ้ำทุกหลักของตัวเลขและหารด้วย 2 แล้วนำเศษที่เหลือมาหารด้วย 2 อีกครั้งในฟังก์ชันหลัก จำนวนที่ต้องการแปลงถูกกำหนดและเรียกใช้ฟังก์ชันโดยส่งตัวเลขนี้เป็นพารามิเตอร์