Convert an integer into a six bit binary string. - Java Language Basics

Java examples for Language Basics:Bit

Description

Convert an integer into a six bit binary string.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int num = 2;
        System.out.println(to6BitBinary(num));
    }/*from w w  w  .  ja v  a  2s.  co m*/

    /**
     * Convert an integer into a six bit binary string.
     * 
     * @param num The int to convert.
     * 
     * @return A six character string that represents the int.
     */
    public static String to6BitBinary(int num) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < 6; i++) {
            sb.append(((num & 1) == 1) ? '1' : '0');
            num >>= 1;
        }

        return sb.reverse().toString();
    }
}

Related Tutorials