Converting String binary to integer - java

How can I do this without using multiplication, division or mod?
I come with the solution but it needs multiplication.
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
value = value * 2 + (int)b.charAt(i) - 48;
}
}
EDIT: SORRY! Only 3 java API are allowed. length(), charAt(), and equals()

Without multiplication, use bitwise shift operator:
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
if(b.charAt(z) == '1'){
shift = b.length()-z-1;
value += (1 << shift);
}
}
}

Use the Integer.valueOf(String, int) method:
Integer.valueOf('10101',2)

Try to use Integer.parseInt(..) like this:
int value = Integer.parseInt(b, 2);
Ofcourse b is a binary String.

You can use the method Integer.parseInt to do this.
String binary = "101010"
int value = Integer.parseInt(binary, 2);
The '2' in Integer.parseInt means to parse the String in base 2.

Related

Attempting to return a fraction (as a float) in Java

In this function:
public float cgRatio(String dna) {
//initialize count to be 0
int count = 0;
//for each character in the string
//if character == 'C' or 'G' increment count
for (int i = 0; i < dna.length(); i++) {
char c = dna.charAt(i);
if (c == 'C' || c == 'G') {
count++;
}
}
//return the ratio of C & G in DNA strand
return count/dna.length();
}
with my test function:
public void testFindGene() {
String[] dnaStrands = new String[6];
dnaStrands[0] = "AGCATGGTAACCAATAAGCGTTAAGCCAT";
dnaStrands[1] = "AATAATGGCATGGCCAATGAATGCGTAACCGATTAA";
dnaStrands[2] = "ATAATGCGGAATTGACATGGTA";
dnaStrands[3] = "AGCATGGTAACCAATTAGCGTTAAGCCAT";
dnaStrands[4] = "AATAATGGCATGGCCAATGAATTGACGTAACCGATTAA";
dnaStrands[5] = "ATAATGCGGAATCTAGACATGGTA";
for (int i = 0; i < dnaStrands.length - 1; i++) {
String gene = findGene(dnaStrands[i], 0);
System.out.println("The DNA strand is: \"" + dnaStrands[i] + "\"");
System.out.println("Gene: " + gene);
System.out.println("CG ratio of gene sequence is: " + String.format("%.02f", cgRatio(gene)));
}
}
My cgRatio return value is always 0.00. If I return just the count, I get accurate results in the form of a float. So that means my cgRatio function fails on this line:
//return the ratio of C & G in DNA strand
return count/dna.length();
Can you not return a fraction in Java? If you can, how can I fix this? If you cannot, why and what is an alternative solution?
try doing as ,
return (float)count/dna.length();
count and length both are int that is why you are getting like that.
Declaring count as a float would also solve the issue. Integer division yield an integer and omits fractions.
float count = 0;
For more clarification as to what is actually happening, the code
return count/dna.length();
is doing integer math then casting the result as a float.
For example if count is 5 and dna.length() returns 7,
5 / 7 = 0.714 which equals 0 when doing integer math (it rounds down to the nearest integer value).
So your code is essentially doing float(0) which gets your result of 0.00.
Cast your variables before dividing return (double)count/(double)dna.length(); Java is making it integer division because both are ints.

In Java, what is the best way to get each individual digit of an integer and its position for comparison?

New to programming: In Java, what is the best way to get each individual digit of an Integer and its position for comparisons? For example, with an input of an Integer i = 12345, I'd like to preform a comparison operation on each individual digit 1, 2, 3, 4, and 5. Since I can't get the index of the integer, I converted the integer to string, iterated, and used charAt().
String sI = Integer.toString(i);
for(int j = 0; j<i; j++){
if(charAt(j)>n){
//do something
}
}
why not try this... you will know that your int is printing from the last digit so you'll know the position.
public static void main(String[] args) {
Integer temp = 123456789;
do {
System.out.println(temp % 10);
temp = temp / 10;
} while (temp % 10 > 0);
}
I would do the same solution however your loop may result in some unexpected errors. That's because i can be greater than the length of your String sI.
And chars in Java are integers too so the comparison may fail: for example the character value of 1 is 49 so a comparison like if (sI.charAt(j) > 10) will always results in true. So you have to re-convert your character to an integer with the Character.getNumericValue() function.
So I'd change the loop to the following:
String sI = Integer.toString(i);
for(int j = 0; j < sI.length(); j++){
if(Character.getNumericValue(sI.charAt(j)) > n){
//do something
}
}
May be something like this helps
public int findallIntegers(int x, int n) {
if(x < 1) return 1;
if(x%10 > n) {
//do some thing
}
return findallIntegers(x/10, n);
}

Comparing two char arrays each representing a binary number

I need to write a method for comparing two binary numbers. I am storing the binary numbers in character arrays, so I can store big numbers (I can't use the BigInteger class or any other packages).
Example to make things clear:
char[] num1 = {'1','1','0'}
char[] num2 = {'1','1','1'}
I need to return 0 if they are equal, -1 if a < b and 1 if a > b
This is the approach I took:
static int compare(char[]a, char[]b) {
//If arrays lengths aren't equal I already know, one is bigger then the other
int a_len = a.length;
int b_len = b.length;
int a_bits = 0;
int b_bits = 0;
if (a_len > b_len)
return 1;
if (b_len > a_len)
return -1;
//I count the number of bits that are 1 in both arrays
for (int i = 0; i < a.length; i++) {
if (a[i] == '1') a_bits++;
if (b[i] == '1') b_bits++;
}
if(a_bits>b_bits)
return 1;
if(b_bits>a_bits)
return -1;
return 0;
}
So as far as I understand, this works in every case, but the case where the number of bits are equal (1100 is bigger than 1001 for example).
I was thinking I could add up the indexes in the for loop for each array and work from there, but I started thinking I may be overcomplicating things. Is this even a good approach to it? I'm starting to doubt it. Any insight is appreciated
I would look for the first index that is 1 in one of the numbers but 0 in the other number. You can replace the bit counting loop(keeping the length check) with:
for (int i = 0; i < a.length; i++) {
if (a[i] == '1' && b[i] == '0') return 1;
if (b[i] == '1' && a[i] == '0') return -1;
}
return 0;
Using some conversion and the binary parseInt offered by class Integer you can do this simple comparison regardless of the arrays' size. (I'd be careful instead with checking the length of the arrays because if you have leading zeros in one array this could bring some comparisons to miss).
String first = new String(a);
String second = new String(b);
int firstint = Integer.parseInt(first, 2);
int secondint = Integer.parseInt(second, 2);
if(firstint > secondint)
return 1;
if(firstint < secondint)
return -1;
return 0;
An alternative approach would be as follows:
Convert Array Of Characters into String.
Convert the resulting String into int.
Work out the logic from the resulting int
It will always work and you can print out the resulting conversion.
Hope this helps.
public static void main(String[] args) {
char[] num1 = {'1','1','0'};
char[] num2 = {'1','1','1'};
System.out.println(compare(num1, num2));
}
public static int compare(char[]num1, char[]num2) {
// Convert Array of Characters to String
String one = String.valueOf(num1);
String two = String.valueOf(num2);
// Convert to Integer (Binary to Decimal Conversion to base2)
int a = Integer.parseInt(one,2);
int b = Integer.parseInt(two,2);
int result = 0; // return result as equals i.e. 0.
if(a > b) { // Yes. Curly brackets are important in Java
result = 1;
} else if(a < b){
result = -1;
}
return result; // Use only one return, i.e. a variable.
}

Why is it returning a negative value for a very long binary string?

public long bin_to_dec() {
int leng = a.length();
for (int i = 0, j = (leng - 1); i < leng; i++, j--) {
int number = Character.getNumericValue(a.charAt(j));
result = result + (number * ((long) Math.pow(2, i)));
}
return result;
}
This code takes a binary string as argument and return it's decimal value .
but for a long string i.e.
(111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111)
it returns -28 .
Why is the memory out of range?
or is my code is incorrect?
You are probably overrunning the length of an int. Integers in java are 32 bit and that binary string is 91 bits.
Try using something like BigInteger instead, which will not overflow. In fact, BigInteger has a built-in method for this:
BigInteger result = new BigInteger(a, 2);

How to convert a binary value to ASCII in JAVA?

This is a homework assignment that I can't wrap my head around. I have to do it manually, so I can't use "getBytes()." Also, I have to convert to decimal format first, and then convert the decimal to ASCII (e.g. {0,1,1,0,0,0,1,0} = 98 in decimal format, which is a 'b'). I have arranged the binary code into an array, and want to use a for loop to traverse the array position by position. However, I'm not sure I'm using the correct parameters for the for loop, and am not sure how to divide the code into bits of "8." Another thing, how to I convert the decimal value to ASCII? Should I just list out all the possible letters I know I will get, and then refer to them using an if-else loop? Or could I just convert the decimal to a char? Here is my code so far... (It's a bit messy, sorry)
class Decoder
{
public void findCode(Picture stegoObj)
{
Pixel pixTar = new Pixel(stegoObj,0,0);
Pixel [] pixelArray = stegoObj.getPixels();
int blueVal = 0;
for(int length = 0; length < pixelArray.length; length++)
{
blueVal = pixTar.getBlue();
}
System.out.println(blueVal);
stegoObj.explore();
}
public void decode(int [] binary)
{
int binaryLen = binary.length;
int totVal = 0;
int newVal = 0;
int bitVal = 0;
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
int exp = x - (binaryLen - 1);
totVal += (pow(bitVal, exp));
}
System.out.println(totVal);
}
}
public class DecodeImage
{
public static void main(String[] args)
{
Picture stegoObj = new Picture("SecretMessage.bmp");
Decoder deco = new Decoder();
int[] binArray = {0,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1,1,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,1,0,1,0,0,0,0,1,1,0,1,0,0,0,0,1,0,1,0};
//int[] binArray = {0,1,1,0,0,0,1,0};
//deco.findCode(stegoObj);
deco.decode(binArray);
}
}
EDIT:
Okay, so I figured out this much, under the class Decoder, in the decode block, in the for loop:
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
preVal = bitVal * base;
totVal += preVal;
base = base * 2;
}
You've got the right idea for decode. I don't see why your code wouldn't work, although I don't see the pow implementation anywhere.
Decimal to ascii is easy, just cast the value to a char:
int v = ...; // decimal value
char c = (char)v; // ascii value
int[] bValue = {1,0,0,0,1,0,1};
int iValue = 0;
// convert binary to decimal
for (int i = 0, pow = bValue.length - 1 ; i < bValue.length ; i++, pow--)
iValue += bValue[i]*Math.pow(2, pow);
// gets the value as a char
char cValue = (char)iValue;
System.out.println("Int value: "+iValue +", Char value : "+cValue);
If you need the whole ASCII table, you may put the values into a Map where the key is the integer value, and the value is the corresponding ASCII entry.

Categories

Resources