Java Binary Encode toBinary(int value, int bits)

Here you can find the source of toBinary(int value, int bits)

Description

Converts an integer to a binary string

License

Open Source License

Parameter

Parameter Description
value The integer value
bits The number of bits to use

Return

The generated string

Declaration

public static String toBinary(int value, int bits) 

Method Source Code

//package com.java2s;
/*//from  ww  w  . j a  v  a2 s .  co  m
 * Copyright (C) 2011 Sony Ericsson Mobile Communications AB
 * Copyright (C) 2012-2013 Sony Mobile Communications AB
 *
 * This file is part of ChkBugReport.
 *
 * ChkBugReport 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.
 *
 * ChkBugReport 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 ChkBugReport.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Converts an integer to a binary string
     * @param value The integer value
     * @param bits The number of bits to use
     * @return The generated string
     */
    public static String toBinary(int value, int bits) {
        StringBuffer sb = new StringBuffer();
        int mask = 1 << (bits - 1);
        for (int i = 0; i < bits; i++) {
            if ((value & mask) == 0) {
                sb.append('0');
            } else {
                sb.append('1');
            }
            mask >>= 1;
        }
        return sb.toString();
    }
}

Related

  1. toBinary(final double d)
  2. toBinary(final Object o)
  3. toBinary(int nr, int bits)
  4. toBinary(int number, int length)
  5. toBinary(int val)
  6. toBinary(long l, int bits)
  7. toBinary(long v, int len)
  8. toBinary(short value)
  9. toBinaryAddress(int index, int maxIndex)