This language bar is your friend. Select your favorite languages!

Idiom #76 Binary digits from an integer

Create the string s of integer x written in base 2.

E.g. 13 -> "1101"

var s = i.toRadixString(2);
import std.conv;
auto s = to!string(13,2);
  Integer.to_string(x, 2)
#include<stdio.h>

int toBinary(int decimalNo);                //convert a integer number in base 10 to binary
int main(void){

 int num;
 scanf("%d",&num);
 int num_converted = toBinary(num); 

 printf("The number %d converted to binary is %d", num, num_converted);
}

int toBinary(int decimalNo){

//Base case
 if(decimalNo < 2) 
   return decimalNo;

//Recursive case
  return toBinary(decimalNo / 2) * 10 + decimalNo % 2;
 
 
}
S = io_lib:format("~.2B~n", [X]).
import "fmt"
import "math/big"
s := fmt.Sprintf("%b", x)
import "strconv"
s := strconv.FormatInt(x, 2)
s x = Numeric.showIntAtBase 2 Data.Char.intToDigit x ""
var base10number = 123

var base2number = base10number.toString(2)
String s = Integer.toBinaryString(x);
local s = {}

while x > 0 do
    local tmp = math.fmod(x,2)
    s[#s+1] = tmp
    x=(x-tmp)/2
end

s=table.concat(s)
$s = sprintf("%b", $x);
StrUtils;
var
  _x: Integer;
  _s: String;
begin
  _s := IntToBin(_x,8*SizeOf(Integer));
end.
var Iter,n:integer;
[...]
  S := '';
  for Iter := 0 to n do
    s:= Char(Ord('0')+(x shr Iter) and 1) + S;   
s = sprintf "%b", 13;
s = '{:b}'.format(x)
s = x.to_s(2)
let s = format!("{:b}", x);

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

deleplace

Related idioms