Showing posts with label shift. Show all posts
Showing posts with label shift. Show all posts

21 June 2010

Two ways to convert decimal numbers to binary strings

I'll show you two ways to convert decimal to binary.

First, the most basic way is apply the following pseudo-code:

int x
char[80] arr
do{
reminder = x%2;
arr[i] = reminder
}while (x/2 > 0);
reverse arr;


And the other is more advanced (and more simple), it use bitwise operations instead:

int x
while (x > 0){
arr[i] = ((x & 1) ? '1' : '0');
x >>=1;
}
reverse arr


and here's a C code for the last one:
 
//I am not the author of this function, I copied from the link below
void dec2binary(long i){

char* str = malloc(sizeof(long)*8*sizeof(char));

char* p = str;
while (i > 0){
*p++ = ((i & 1) ? '1' : '0');
i >>=1;
}

while( p-- != str ) /* print out the result backwards */
printf("%c",*p);

free(str);
}


please see:
http://www.daniweb.com/code/snippet216349.html

20 May 2010

Shift operators in Java

Here's a very simple lesson that illustrate the shift operators in java

http://www.sap-img.com/java/java-bitwise-shift-operators.htm

Summary:

We have three shift operators in java >>, >>> and <<

1- >>
definition:
right shift with the outermost (hi bit) value
example:
9>> 2
9 in binary is 0000000000001001
so, we need to shift right 2 bites adding instead 2 bits of the hi bit
so, result will be 0000000000000010

2- >>>
It is the same as the above, but adds 0 at the left most (not the hi bit)
so, suppose we have
-1 >> 2
-1 in binary is 1111111111111111 (the 2's complement of 1)
so, the result will be -1 also. but if we applied >>> instead, we will always add 0's to the left of the bit pattern.

3- <<
left right is the oposite to the left shift (<<), that add the hi bit from the right.
ex:
9 << 1
9 in binary is 0000000000001001
result will be 0000000000010010 (in decimal is 18 )

(please let me know if there's any errors because I wrote that conclusion in hurry ;) )