Saturday, January 1, 2011

Two's complement to Decimal in JAVA

I was searching for a way to convert two's complement to Decimal in JAVA , it seems like there is no built-in method to do this. So I wrote a code , probably this is not the most efficient way to do it , but you can use it if u are desperate and have no time to write your own version.



//----------------JAVA code-------------------------------------
package de.vogella.android.locationapi.maps;

public class TwosToInt {

private static int[] latIntArrayNew = new int[32];
private static String[] latStringArray = new String[32];
private static int latDec;
private static String latStringString;
/**
* @param args
*/
public static String twostoint(int[] latIntArray) {
int kk = latIntArray[0];
if(kk==1){
//---convert-----------
for(int i=0;i<32;i++){

//--- binary NO operation
if(latIntArray[i]==0){latIntArrayNew[i]=1;}
else{latIntArrayNew[i]=0;}

}
}else{

latIntArrayNew = latIntArray;
}

for(int j=0;j<32;j++){latStringArray[j] = Integer.toString(latIntArrayNew[j]);}

latStringString = arrayToString2(latStringArray);

//--add 1 after the NO operation
latDec = 0;
if(kk==1){
latDec = (( Integer.parseInt(latStringString,2))+1)*(-1);
}else{
latDec = ( Integer.parseInt(latStringString,2)+1);
}

return Integer.toString(latDec);
//Integer.toString(latDec);
//latStringString;



}

public static String arrayToString2(String[] a) {
StringBuffer result = new StringBuffer();
if (a.length > 0) {
for (int i=0; i result.append(a[i]);
}
}

return result.toString();
}


}

No comments: