I need to convert desimal number to 7 bit binary. Like the binary of 11(desimal) is 001011.
I did found a solution in starkoverflow but it doesn't work like i want
String dec2bin(int dec) {
var bin = '';
while (dec > 0) {
bin = (dec % 2 == 0 ? '0' : '1') bin;
dec ~/= 2;
}
return bin;
}
it returns 1011
, cuts all the zeros before 1011
How can i solve that?
CodePudding user response:
Just use padLeft
on the String
before returning it to make sure it is a minimum length prefixed with zeros. Also, your dec2bin
method can be simplified into just using toRadixString(2)
on your input integer. So something like this:
String dec2bin(int dec) => dec.toRadixString(2).padLeft(6, '0');
void main() {
print(dec2bin(11)); // 001011
}