Java Long to longToBinary(long num)

Here you can find the source of longToBinary(long num)

Description

A quick method to convert num to a binary number.

License

Open Source License

Parameter

Parameter Description
num The number to convert

Declaration

public static String longToBinary(long num) 

Method Source Code

//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
    }
}

Related

  1. longToBaseCode(char[] target, int targetOffset, long value, int base, int lengthLimit, boolean fillZeros, boolean upperCase)
  2. longToBasicType(long l, Class clazz)
  3. longToBcd(long num, int size)
  4. longToBcd(long src, int len, int flag)
  5. longToBigEndian(long value, byte[] in, int offset)
  6. longtobinarystring(long wert, int bits)
  7. longToBinaryStringUnsigned(long value)
  8. longToBucket(long key, int buckets)
  9. LongToBuf4(long val, byte[] buf, int offset)