Here you can find the source of longToBinary(long num)
num
to a binary number.
Parameter | Description |
---|---|
num | The number to convert |
public static String longToBinary(long num)
//package com.java2s; /* This file is part of Math4J. * Math4J is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version./*from w w w .ja v a 2 s. c o m*/ * * Math4J is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Math4J; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * Copyright 2005 Anthony Magee */ public class Main { /** * A quick method to convert <code>num</code> to a binary number. A binary * number contains only ones and zeroes. * * @param num The number to convert */ public static String longToBinary(long num) { /* * StringBuffer returnBuf = new StringBuffer(64); // storage for output * value * * long power = 0; // the highest power of two while(num > (long) * Math.pow(2, power)) { // test if 2^power is greater than number * power++; // if so increase power by one until it is not } * * for(long i = power; i >= 0L; i--) { // loop through all valid powers * if((num / (long) Math.pow(2, i)) >= 1) // if 2^power is valid divisor * returnBuf.append("1"); // append a bit else returnBuf.append("0"); // * else append an empty bit * * num %= (long) Math.pow(2, i); // decrease number by its highest * disivor of two } */ return Long.toString(num, 2); // return the binary number as a string // because of length } }