Logo

Programming-Idioms

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"

import "fmt"
import "math/big"
s := fmt.Sprintf("%b", x)
import "strconv"
s := strconv.FormatInt(x, 2)
(:require [clojure.pprint])
(defn s
  [x]
  (pprint/cl-format nil "~b" x))
#include <bitset>
std::bitset<sizeof(x)*8> y(x);
auto s = y.to_string();
#include <charconv>
std::string ToBinary(int x) {
  std::array<char, 64> buf;
  auto[ptr, ec] = std::to_chars(buf.data(), buf.data() + buf.size(), x, 2);
  auto s = std::string(buf.data(), ptr);
  return s;
}
String s = Convert.ToString(x,2).PadLeft(16, '0');
String s = Convert.ToString(x,2);
import std.conv;
auto s = to!string(x,2);
var s = x.toRadixString(2);
Integer.digits(x, 2) |> Enum.join("")
s = Integer.to_string(x, 2)
S = io_lib:format("~.2B~n", [X]).
write (unit=s,fmt='(B32)') x
write (unit=s,fmt='(B0)') x
import Data.List
foldl (\acc -> (++ acc) . show) "" . unfoldr (\n -> if x == 0 then Nothing else Just (x `mod` 2, x `div` 2))
import Numeric (showIntAtBase)
import Data.Char (intToDigit)
s x = showIntAtBase 2 intToDigit x ""
let s = x.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);
var Iter,n:integer;
[...]
  S := '';
  for Iter := 0 to n do
    s:= Char(Ord('0')+(x shr Iter) and 1) + S;   
uses StrUtils;
var
  _x: Integer;
  _s: String;
begin
  _s := IntToBin(_x,8*SizeOf(Integer));
end.
$s = sprintf "%b", $x;
s = '{:b}'.format(x)
s = x.to_s(2)
let s = format!("{x:b}");
let s = format!("{:b}", x);
val s = x.toString(2)
(define (binary-representation x)
  (let loop ([N x]
             [s '()])
    (let ([NN (arithmetic-shift N -1)])
      (cond [(zero? N) (list->string s)]
            [(odd? N) (loop NN (cons #\1 s))]
            [else (loop NN (cons #\0 s))]))))

New implementation...