An 8-bit representation of decimal Numbers in java - java

I am currently struggling with an exercise that would convert a signed decimal number between -128 and +127 to its 8-bit binary representation in the two’s complement number system.
I am able to get a representation of the positive numbers, however when the code runs for the input to be a negative, it does the computation, but I am unable to get the right Binary repersentation. For example "57" in 8-bit repersentation would be "00111001" and -57 in the same repersentation would be "11000111"
I am pretty sure I have to do an if statement however I can not get it to work. Very lost
System.out.println("Please enter a decimal to modify into it's binary.");
decimalInput = stdIn.nextInt();
if (decimalInput < 0){
decimalInput= Math.abs(decimalInput);
if(i==0){
binary[i]=1;
}else if (i==1){
binary[i] = 0;
}
}
for ( i = binary.length-1; i >= 0; i--){
remain = decimalInput % 2;
binary[i]=remain;
decimalInput = decimalInput / 2;
}
for (i =0; i <8; i++){
System.out.print(binary[i]);
}

That's because you are again computing the binary of a number in the next for loop with decimalInput (post you take absolute value of decimal number and convert that number to binary). You are repeating the same for loop.
You could do something like:
int computeValue = decimalInput;
if (decimalInput < 0){
computeValue= Math.abs(decimalInput);
}
for (...){
negRemain = computeValue% 2;
...
}
EDIT for 2s complement:
if (decimalInput < 0) {
handleNegativeNumbers(binary);
}
private static void onesComplements(int[] binary) {
for (int i = 0; i < binary.length; i++) {// will perform one's complement
if (binary[i] == 0) {
binary[i] = 1;
} else {
binary[i] = 0;
}
}
}
private static void twosComplement(int[] binary) {
int carry = 1;
for (int i = binary.length - 1; i >= 0; i--) {// will perform two's complement by adding one
if (carry == 1) {
if (binary[i] == 0) {
binary[i] = 1;
carry = 0;
break;
} else {
binary[i] = 0;
}
}
}
}
private static void handleNegativeNumbers(int[] binary) {
onesComplements(binary);
twosComplement(binary);
}

Related

Algorithm to find prime numbers with odd digits in large range

Given a range of [1, 1000000000] we need to find prime numbers and all the digits of the prime number must be odd. (Example: 23 is not okay, 31 is okay)
If we go on by looping through each number and checking if it is prime etc, it is very slow. Is there a way to make this close to O(N) ?
I tried to eliminate as much as possible by looking at digits first. But after eliminating numbers with even digits the prime test is too slow.
for all numbers in [1, N]
check all digits, if any even digit, continue
check primality (this step is very slow)
And the primality test should not be very complex (probabilistic etc. is not possible, it must be possible to implement in a few minutes). The one I use is:
private static boolean isPrime(int n) {
boolean isPrime = true;
for (int divisor = 2; divisor <= n / 2; divisor++) {
if (n % divisor == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
Maybe there is a trick to ensure a quick primality test but I couldn't find. Any suggestions? Thanks for reading.
You don't need to check all milliard numbers. Generate all numbers with only odd digits - there are at most 5^9~2 millions of them. Exclude those ending with 5 and not generate numbers divisible by 3 (in the moment of the last digit generation)
Then check these numbers for primality. Note that loop limit might be sqrt(n)
Ideone
class Ideone
{
static int oddcnt;
public static void checkprime(int x) {
for (int i=3; i <= Math.sqrt(x); i +=2)
if ((x % i) == 0)
return;
oddcnt++;
}
public static void genodd(int x, int curlen, int maxlen) {
x *= 10;
for (int i=1; i<10; i+=2) {
int nx = x + i;
checkprime(nx);
if (curlen < maxlen)
genodd(nx, curlen + 1, maxlen);
}
}
public static void main (String[] args) throws java.lang.Exception
{
genodd(0, 1, 8);
System.out.println(oddcnt);
}
}
The best way I can think of is to run a Prime Sieve of Eratosthenes to find all the primes in the range (0; sqrt(1000000000)) - which is around (0, 31622) - and time complexity O(n*log(log(n))) where n=31622. We will need those prime for a faster primality test.
Then, just loop through each number with odd digits - there are 5^10 = 9765625 ~ 10000000 such numbers. You saved 1000 times compared to iterating through all number in the original range.
The primality test using the primes we found in step 1 can be fast, as you only need to check with primes < sqrt(n), and you already have the primes. Even for the largest number in the range which is 999999999, the number of candidate primes is just 3432.
The following is a Java implementation
public class Execute {
private ArrayList<Long> primes = new ArrayList<>();
#org.junit.Test
public void findOddDecimalPrimes() {
primeSieve(32000);
System.out.println(primes.size());
for (int i = 0; i < 9765625; i++) {
String inBase5 = convertFromBaseToBase(i);
long evenDec = convertToOddDecimal(inBase5);
if (isPrime(evenDec)) {
System.out.println(evenDec);
}
}
}
private String convertFromBaseToBase(long i) {
return Long.toString(i, 5);
}
private long convertToOddDecimal(String str) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
s.append(1 + 2 * Integer.parseInt("" + str.charAt(i)));
}
return Long.parseLong(s.toString());
}
private boolean isPrime(long n) {
for (int i = 0; i < primes.size(); i++) {
if (primes.get(i) * primes.get(i) > n) break;
long divisor = n / primes.get(i);
if (divisor * primes.get(i) == n) return false;
}
return true;
}
/**
* References: www.geeksforgeeks.org
*/
private void primeSieve(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
boolean prime[] = new boolean[n+1];
for(int i=0;i<n;i++)
prime[i] = true;
for(int p = 2; p*p <=n; p++)
{
// If prime[p] is not changed, then it is a prime
if(prime[p] == true)
{
// Update all multiples of p
for(int i = p*p; i <= n; i += p)
prime[i] = false;
}
}
for (int i = 2; i < prime.length; i++) {
if (prime[i]) this.primes.add(Long.valueOf(i));
}
}
}
If your numbers are in order, you can optimize your isPrime function.
Here is a js sample version.
var primes = [];
function checkDigits(n) {
while(n > 1) {
var d = n % 10;
if ( d % 2 == 0) { return false; }
n = parseInt(n/10,10);
}
return true;
}
function isPrime(n) {
for(var i = 1; i < primes.length; i++) {
if(n % primes[i] == 0) {
return false;
}
}
var lastPrime = primes.length > 2 ? primes[primes.length - 1] : 1;
var inc = 2;
for(var i = lastPrime + inc; i < Math.sqrt(n); i += inc) {
if(n % i == 0) {
return false;
}
}
primes.push(n);
return true;
}
for(var i = 1; i < 100; i++) {
if(checkDigits(i) && isPrime(i)) {
console.log(i);
}
}
This is an open question in math and computer science in general.
In a nutshell no, there is no know way to solve that problem in O(1) to get your loop running in O(N) over the whole range.
If you solve that, dont tell anyone, and go get rich by breaking most of the encryptions today that use large prime numbers.
What you could do though, is make the loop over the devisor a bit smaller by useing sqrt(n).
That will bring that inner loop down from O(N^2) to O(sqrt(N))
And the whole complexity from O(N^2) to O(N*sqrt(N))=O(N^(3/2))
Anotger optimization would be to check the odd digits first beforre doing the complex Prime calculation

How to convert int number to two numbers witch first is made by odd bits and 2nd by even bits

How can I convert int=43707 to two other numbers?
The first number is made by value of odd bits. Second number is made by value of even bits.
int x = 43707; // 1010101010111011
var even = 0;
var odd = 0;
for (int i = 0; i<=31; i++) {
if(i%2 == 0) {
?
} else {
?
}
}
Your looking for the bitwise AND operation: &. you can use it together with a binary mask (normally specified in hex notation 0x00FF). so you need to do something like:
int x= 707; //10110011
int oddBits = 0x5555; //01010101
int evenBits = 0xAAAA; //10101010
int oddResult = x & oddBits;
System.out.println(oddResult);
int evenResult = x & evenBits;
System.out.println(evenResult);
which returns: 65 //00010001
and 642 // 10100010
Just convert int into digits as shown below:
List<Integer> digits = new ArrayList<Integer>();
while(x > 0) {
digits.add(x % 10);
x /= 10;
}
System.out.println(digits);
Once you have the separated the digits then apply the even odd logic. Here is complete code:
int x = 43707; // 1010101010111011
List<Integer> digits = new ArrayList<>();
while(x > 0) {
digits.add(x % 10);
x /= 10;
}
int i = 0;
int length = digits.size();
while (i < length) {
if(digits.get(i)%2 == 0){
System.out.println("Even Number" + digits.get(i));
} else {
System.out.println("Odd Number" + digits.get(i));
}
i++;
}
If you are looking for the Binary conversion then you can use the below code.
int x = 43707; // 1010101010111011
int testNumber;
String binaryNumber = Integer.toBinaryString(x);
for (int i = 0 ; i != binaryNumber.length() ; i++) {
char c = binaryNumber.charAt(i);
testNumber = Character.getNumericValue(binaryNumber.charAt(i));
if(testNumber == 0){
System.out.println("Even Number");
} else {
System.out.println("Odd Number");
}
System.out.println(c);
}
System.out.println(binaryNumber);
It converts the Int to Binary and then check even and odd numbers.
Hope, it works for you as per your desired output.
I came up to this:
int x = 43707;
String binary = Integer.toBinaryString(x);
System.out.println("binary=" + binary);
String odds = "";
String evens = "";
for (int i = binary.length() - 1; i >= 0; i--) {
if ((i + 1) % 2 == 0) {
odds += binary.charAt(i);
} else {
evens += binary.charAt(i);
}
}
System.out.println("odds=" + odds);
System.out.println("evens=" + evens);
int odd = Integer.parseInt(odds, 2);
int even = Integer.parseInt(evens, 2);
System.out.println("number from odd bits=" + odd);
System.out.println("number from even bits=" + even);
prints
binary=1010101010111011
odds=10100000
evens=11111111
number from odd bits=160
number from even bits=255
I'm counting right to left the bits.

I want to know if this is a good programming practise else how can i write the program more optimal and efficient

I want to write the program of converting decimal to binary and then find number of consecutive 1s in it without using fuctions such as Integer.toBinary(), etc.
my program :
public class Practise {
static String decimalToBinary(int num) {
String binaryN = "";
while (true) {
binaryN += num % 2;
num = num / 2;
if (num == 1) {
binaryN += 1;
break;
}
}
String nBinary = "";
for (int i = binaryN.length() - 1; i >= 0; i--) {
nBinary += binaryN.charAt(i);
}
System.out.println(nBinary);
return nBinary;
}
static int consecutiveOnes(String binaryN) {
int consecutive = 0;
int max = 0;
boolean isFreshStart = false;
for (int i = 0; i < binaryN.length(); i++) {
if (binaryN.charAt(i) == '1') {
if (isFreshStart) {
consecutive = 1;
isFreshStart = false;
} else
consecutive++;
} else {
isFreshStart = true;
}
if (consecutive > max)
max = consecutive;
}
return max;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String binaryN = decimalToBinary(n);
System.out.println(consecutiveOnes(binaryN));
}
}
Is my Program Optimal if not then how can if be more optimal ,thanks in advance.
If your goal is to count consecutive 1s,
then it's best not to convert into a binary string at all.
You can iterate over the bits using bit shifting:
int work = num;
while (work > 0) {
int bit = work & 1;
work >>= 1;
// Todo: count consecutive 1s
}
This approach will use much less storage (essentially a single int instead of a String), and work much faster without creating additional objects and unnecessary intermediate type conversions.

Manually converting a string to an integer in Java

I'm having string consisting of a sequence of digits (e.g. "1234"). How to return the String as an int without using Java's library functions like Integer.parseInt?
public class StringToInteger {
public static void main(String [] args){
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public int myStringToInteger(String str){
/* ... */
}
}
And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers, if the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
If the standard libraries are disallowed, there are many approaches to solving this problem. One way to think about this is as a recursive function:
If n is less than 10, just convert it to the one-character string holding its digit. For example, 3 becomes "3".
If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit. Recursively get a string for the first digits, then append the appropriate character for the last digit. For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".
You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.
Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)
Hope this helps!
Use long instead of int in this case.
You need to check for overflows.
public static int StringtoNumber(String s) throws Exception{
if (s == null || s.length() == 0)
return 0;
while(s.charAt(0) == ' '){
s = s.substring(1);
}
boolean isNegative = s.charAt(0) == '-';
if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
s = s.substring(1);
}
long result = 0l;
for (int i = 0; i < s.length(); i++){
int value = s.charAt(i) - '0';
if (value >= 0 && value <= 9){
if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
throw new Exception();
}else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
throw new Exception();
}
result = 10 * result + value;
}else if (s.charAt(i) != ' '){
return (int)result;
}
}
return isNegative ? -1 * (int)result : (int)result;
}
Alternate approach to the answer already posted here. You can traverse the string from the front and build the number
public static void stringtoint(String s){
boolean isNegative=false;
int number =0;
if (s.charAt(0)=='-') {
isNegative=true;
}else{
number = number* 10 + s.charAt(0)-'0';
}
for (int i = 1; i < s.length(); i++) {
number = number*10 + s.charAt(i)-'0';
}
if(isNegative){
number = 0-number;
}
System.out.println(number);
}
Given the right hint, I think most people with a high school education can solve this own their own. Every one knows 134 = 100x1 + 10x3 + 1x4
The key part most people miss, is that if you do something like this in Java
System.out.println('0'*1);//48
it will pick the decimal representation of character 0 in ascii chart and multiply it by 1.
In ascii table character 0 has a decimal representation of 48. So the above line will print 48. So if you do something like '1'-'0' That is same as 49-48. Since in ascii chart, characters 0-9 are continuous, so you can take any char from 0 to 9 and subtract 0 to get its integer value. Once you have the integer value for a character, then converting the whole string to int is straight forward.
Here is another one solution to the problem
String a = "-12512";
char[] chars = a.toCharArray();
boolean isNegative = (chars[0] == '-');
if (isNegative) {
chars[0] = '0';
}
int multiplier = 1;
int total = 0;
for (int i = chars.length - 1; i >= 0; i--) {
total = total + ((chars[i] - '0') * multiplier);
multiplier = multiplier * 10;
}
if (isNegative) {
total = total * -1;
}
Use this:
static int parseInt(String str) {
char[] ch = str.trim().toCharArray();
int len = ch.length;
int value = 0;
for (int i=0, j=(len-1); i<len; i++,j--) {
int c = ch[i];
if (c < 48 || c > 57) {
throw new NumberFormatException("Not a number: "+str);
}
int n = c - 48;
n *= Math.pow(10, j);
value += n;
}
return value;
}
And by the way, you can handle the special case of negative integers, otherwise it will throw exception NumberFormatException.
You can do like this: from the string, create an array of characters for each element, keep the index saved, and multiply its ASCII value by the power of the actual reverse index. Sum the partial factors and you get it.
There is only a small cast to use Math.pow (since it returns a double), but you can avoid it by creating your own power function.
public static int StringToInt(String str){
int res = 0;
char [] chars = str.toCharArray();
System.out.println(str.length());
for (int i = str.length()-1, j=0; i>=0; i--, j++){
int temp = chars[j]-48;
int power = (int) Math.pow(10, i);
res += temp*power;
System.out.println(res);
}
return res;
}
Using Java 8 you can do the following:
public static int convert(String strNum)
{
int result =strNum.chars().reduce(0, (a, b)->10*a +b-'0');
}
Convert srtNum to char
for each char (represented as 'b') -> 'b' -'0' will give the relative number
sum all in a (initial value is 0)
(each time we perform an opertaion on a char do -> a=a*10
Make use of the fact that Java uses char and int in the same way. Basically, do char - '0' to get the int value of the char.
public class StringToInteger {
public static void main(String[] args) {
int i = myStringToInteger("123");
System.out.println("String decoded to number " + i);
}
public static int myStringToInteger(String str) {
int sum = 0;
char[] array = str.toCharArray();
int j = 0;
for(int i = str.length() - 1 ; i >= 0 ; i--){
sum += Math.pow(10, j)*(array[i]-'0');
j++;
}
return sum;
}
}
public int myStringToInteger(String str) throws NumberFormatException
{
int decimalRadix = 10; //10 is the radix of the decimal system
if (str == null) {
throw new NumberFormatException("null");
}
int finalResult = 0;
boolean isNegative = false;
int index = 0, strLength = str.length();
if (strLength > 0) {
if (str.charAt(0) == '-') {
isNegative = true;
index++;
}
while (index < strLength) {
if((Character.digit(str.charAt(index), decimalRadix)) != -1){
finalResult *= decimalRadix;
finalResult += (str.charAt(index) - '0');
} else throw new NumberFormatException("for input string " + str);
index++;
}
} else {
throw new NumberFormatException("Empty numeric string");
}
if(isNegative){
if(index > 1)
return -finalResult;
else
throw new NumberFormatException("Only got -");
}
return finalResult;
}
Outcome:
1) For the input "34567" the final result would be: 34567
2) For the input "-4567" the final result would be: -4567
3) For the input "-" the final result would be: java.lang.NumberFormatException: Only got -
4) For the input "12ab45" the final result would be: java.lang.NumberFormatException: for input string 12ab45
public static int convertToInt(String input){
char[] ch=input.toCharArray();
int result=0;
for(char c : ch){
result=(result*10)+((int)c-(int)'0');
}
return result;
}
Maybe this way will be a little bit faster:
public static int convertStringToInt(String num) {
int result = 0;
for (char c: num.toCharArray()) {
c -= 48;
if (c <= 9) {
result = (result << 3) + (result << 1) + c;
} else return -1;
}
return result;
}
This is the Complete program with all conditions positive, negative without using library
import java.util.Scanner;
public class StringToInt {
public static void main(String args[]) {
String inputString;
Scanner s = new Scanner(System.in);
inputString = s.nextLine();
if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
System.out.println("error!!!");
} else {
Double result2 = getNumber(inputString);
System.out.println("result = " + result2);
}
}
public static Double getNumber(String number) {
Double result = 0.0;
Double beforeDecimal = 0.0;
Double afterDecimal = 0.0;
Double afterDecimalCount = 0.0;
int signBit = 1;
boolean flag = false;
int count = number.length();
if (number.charAt(0) == '-') {
signBit = -1;
flag = true;
} else if (number.charAt(0) == '+') {
flag = true;
}
for (int i = 0; i < count; i++) {
if (flag && i == 0) {
continue;
}
if (afterDecimalCount == 0.0) {
if (number.charAt(i) - '.' == 0) {
afterDecimalCount++;
} else {
beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
}
} else {
afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
afterDecimalCount = afterDecimalCount * 10;
}
}
if (afterDecimalCount != 0.0) {
afterDecimal = afterDecimal / afterDecimalCount;
result = beforeDecimal + afterDecimal;
} else {
result = beforeDecimal;
}
return result * signBit;
}
}
Works for Positive and Negative String Using TDD
//Solution
public int convert(String string) {
int number = 0;
boolean isNegative = false;
int i = 0;
if (string.charAt(0) == '-') {
isNegative = true;
i++;
}
for (int j = i; j < string.length(); j++) {
int value = string.charAt(j) - '0';
number *= 10;
number += value;
}
if (isNegative) {
number = -number;
}
return number;
}
//Testcases
public class StringtoIntTest {
private StringtoInt stringtoInt;
#Before
public void setUp() throws Exception {
stringtoInt = new StringtoInt();
}
#Test
public void testStringtoInt() {
int excepted = stringtoInt.convert("123456");
assertEquals(123456,excepted);
}
#Test
public void testStringtoIntWithNegative() {
int excepted = stringtoInt.convert("-123456");
assertEquals(-123456,excepted);
}
}
//Take one positive or negative number
String str="-90997865";
//Conver String into Character Array
char arr[]=str.toCharArray();
int no=0,asci=0,res=0;
for(int i=0;i<arr.length;i++)
{
//If First Character == negative then skip iteration and i++
if(arr[i]=='-' && i==0)
{
i++;
}
asci=(int)arr[i]; //Find Ascii value of each Character
no=asci-48; //Now Substract the Ascii value of 0 i.e 48 from asci
res=res*10+no; //Conversion for final number
}
//If first Character is negative then result also negative
if(arr[0]=='-')
{
res=-res;
}
System.out.println(res);
public class ConvertInteger {
public static int convertToInt(String numString){
int answer = 0, factor = 1;
for (int i = numString.length()-1; i >= 0; i--) {
answer += (numString.charAt(i) - '0') *factor;
factor *=10;
}
return answer;
}
public static void main(String[] args) {
System.out.println(convertToInt("789"));
}
}

Convert a large 2^63 decimal to binary

I need to convert a large decimal to binary how would I go about doing this? Decimal in question is this 3324679375210329505
How about:
String binary = Long.toString(3324679375210329505L, 2);
You may want to go for BigDecimal.
A BigDecimal consists of an arbitrary
precision integer unscaled value and a
32-bit integer scale.The BigDecimal class provides operations for arithmetic, scale
manipulation, rounding, comparison, hashing, and format conversion. The toString() method
provides a canonical representation of a BigDecimal.
new BigDecimal("3324679375210329505").toString(2);
http://www.wikihow.com/Convert-from-Decimal-to-Binary
I would use a Stack! Check if your decimal number is even or odd, if even push a 0 to the stack and if its odd push a 1 to the stack. Then once your decimal number hits 1, you can pop each value from the stack and print each one.
Here is a very inefficient block of code for reference. You will probably have to use long instead of integer.
import java.util.Stack;
public class DecBinConverter {
Stack<Integer> binary;
public DecBinConverter()
{
binary = new Stack<Integer>();
}
public int dec_Bin(int dec)
{
if(dec == 1)
{
System.out.print(1);
return 0;
}
if(dec == 0)
{
System.out.print(0);
return 0;
}
if((dec%2) == 0)
{
binary.push(0);
dec = dec/2;
}
else
{
binary.push(1);
dec = dec/2;
}
while(dec != 1)
{
if((dec%2) == 0)
{
binary.push(0);
dec = dec/2;
}
else
{
binary.push(1);
dec = dec/2;
}
}
if((dec%2) == 0)
{
binary.push(0);
dec = dec/2;
}
else
{
binary.push(1);
dec = dec/2;
}
int x = binary.size();
for(int i = 0; i < x; i++)
{
System.out.print(binary.pop());
}
return 0;
}
}
If you want something fast (over 50% faster than Long.toString(n, 2) and 150-400% faster than BigInteger.toString(2)) that handles negative numbers the same as the built-ins, try the following:
static String toBinary (long n) {
int neg = n < 0 ? 1 : 0;
if(n < 0) n = -n;
int pos = 0;
boolean[] a = new boolean[64];
do {
a[pos++] = n % 2 == 1;
} while ((n >>>= 1) != 0);
char[] c = new char[pos + neg];
if(neg > 0) c[0] = '-';
for (int i = 0; i < pos; i++) {
c[pos - i - 1 + neg] = a[i] ? '1' : '0';
}
return new String(c);
}
If you want the actual Two's Compliment binary representation of the long (with leading 1s or 0s):
static String toBinaryTC (long n) {
char[] c = new char[64];
for(int i = 63; i >= 0; i--, n >>>= 1) {
c[i] = n % 2 != 0 ? '1' : '0';
}
return new String(c);
}
A bit pointless, but here is a solution in C:
void to_binary(unsigned long long n)
{
char str[65], *ptr = str + 1;
str[0] = '\n';
do{
*ptr++ = '0' + (n&1);
} while(n >>= 1);
while(ptr > str)
putc(*--ptr, stdout);
}
For the example, it prints out:
10111000100011101000100100011011011111011110101011010110100001
EDIT: And if you don't mind leading zeros....
void to_binary(unsigned long long n)
{
do{ putc('0' + (n>>63), stdout); } while(n <<= 1);
}

Categories

Resources