0

I want to display the given number in binary format. For example 78 -> 1001110

1
  • 1
    Welcome to SFSE! Please take the tour and read How to Ask. This site isn't a code-writing service, and it works best when you have a specific issue and can show us what you've tried and where you're stuck. Please edit your question to show us what you've tried and what research you've done.
    – Derek F
    Jan 14 at 13:43
3

You can use any existing algorithm and implement it in the apex. For example

public static String intToBinary(Integer n) {
    String s = '';
    while (n > 0)
    {
        s =  ((Math.mod(n, 2)) == 0 ? '0' : '1') + s;
        n = n / 2;
    }
    return s;
}

usage:

System.debug(intToBinary(78));

Result:

|DEBUG|1001110


thanks for @sfdcfox in the comments. Here is an optimized version of it

public static String intToBinary(Integer n) {
    String s = '';
    while(n != 0) {
        s = (n & 1) + s;
        n >>>= 1;
    }
    return s;
}
1
  • 1
    My previous comment had a bug, too. The function should have been public String intToBin(Integer n) { String s = ''; while(n != 0) { s = (n & 1) + s; n >>>= 1; } return s; } the >>= should have been >>>=.
    – sfdcfox
    Jan 14 at 14:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.