Decimal (String) to Binary?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 18 19:49:12 UTC 2018


On Thu, Oct 18, 2018 at 07:26:08PM +0000, MDtox via Digitalmars-d wrote:
> How to convert decimal and string to binary?

What exactly do you mean by "binary"?  If you mean convert a string to a
numerical type, use std.conv.to:

	import std.conv : to;
	auto x = "12345";
	auto i = x.to!int;
	assert(i == 12345);

If you want to print a decimal string in binary:

	import std.stdio;
	auto x = "12345";
	auto i = x.to!int;
	writefln("%b",  i);	// prints: 11000000111001

Or if you want the binary representation in string form:

	import std.format : format;
	auto x = "12345";
	auto i = x.to!int;
	auto s = format("%b",  i);
	assert(s == "11000000111001");


T

-- 
Let's not fight disease by killing the patient. -- Sean 'Shaleh' Perry


More information about the Digitalmars-d mailing list