How sum byte array with for loop? - java

This works!
Array lenght is 8
int crc = (bin[1] + bin[2] + bin[3] + bin[4] + bin[5] + bin[6]) & 0Xff;
the problem is that receive data length may vary.
and i try calculate the checksum with loop, but i dont get it work.
byte crc = 0;
for (int i = 1; i < bin.length - 2; i++) {
crc += bin[i];
}
int crcI = crc & 0xff;
this usually gives wrong values, but sometimes they are correct

This check:
i < bin.length - 2
evaluates to:
i < 8 - 2
ie
i < 6
ie the last element to be taken into account is at index 5, not 6.
If you are trying to get the sum of every byte except the first and the last one, then you should probably use:
for (int i = 1; i < bin.length - 1; i++) {
...
}
or, change your < operator to <=, like so:
for (int i = 1; i <= bin.length - 2; i++) {
...
}
An example when the result may be correct in the code you gave in your question is if the element at index 6 (ie bin[6]) is equal to 0 (and that's because 0 will not contribute to a sum).

Related

How to add zeros to the end of value of Long object [duplicate]

for(i=0; i<array.length; i++){
sum = 4 * 5;
}
What I'm trying to do is add ((array.length - 1) - i) 0's to the value of sum. For this example assume array length is 3. sum equals 20. So for the first iteration of the loop i want to add ((3 - 1) - 0) 0's to the value of sum, so sum would be 2000. The next iteration would be ((3 - 1) - 1) 0's. so sum would equal 200 and so on. I hope what I am trying to achieve is clear.
So my questions are:
Is it possible to just shift an int to add extra digits? My search thus far suggests it is not.
If not, how can i achieve my desired goal?
Thankyou for reading my question and any help would be greatly apreciated.
You can just multiply it by 10 however many times.
200 * 10 = 2000
etc
So in your case, you'd have to use a for loop until the end of the array and multiply sum every iteration. Be careful though, because the max value of an int is 2^31, so it of surpasses that, it will roll back to 0
You can add n zeroes to the end of a number, sum by multiplying sum by 10 * n.
int sum = 20;
for (int i = 0; i < ary.length; ++i) {
int zeroesToAdd = ary.length - 1 - i
sum *= (zeroesToAdd > 0) ? zeroesToAdd * 10 : 1
}
System.out.println("Sum after loop: " + sum);
for(int i=array.length; i>0; i--){
sum = 20;
for(int j=0; j < (i - 1); j++)
{
sum *= 10;
}
}
Use inner loop to multiply by 10 the number of times i is for that iteration. You would need to reset sum in your outer loop each time.
You will want to check your for-loop condition: i>array.length. Since i starts at 0, this loop will not run unless the array's length is also 0 (an empty array). The correct condition is i < array.length.
This "shift" you want can be achieved by creating a temporary variable inside the loop that is equal to the sum times 10i. In Java's Math library, there is a pow(a,b) function that computes ab. With that in mind, what you want is something like this:
int oldSum = 4 * 5;
for (int i = 0; i < array.length; i++) {
int newSum = oldSum * Math.pow(10,i);
}
Multiply by 10 instead, and use < (not >) like
int sum = 20;
int[] array = { 1, 2, 3 };
for (int i = 0; i < array.length; i++) {
int powSum = sum;
for (int j = array.length - 1; j > i; j--) {
powSum *= 10;
}
System.out.println(powSum);
}
Output is (as requested)
2000
200
20
For array of length = n; you will end up adding (n - 1) + (n - 2) + ... + 2 + 1 + 0 zeros for i = 0, 1, ... n-2, n-1 respectively.
Therefore, number of zeros to append (z) = n * (n-1) / 2
So the answer is sum * (10 ^ z)
[EDIT]
The above can be used to find the answer after N iteration. (I miss read the question)
int n = array.length;
long sum = 20;
long pow = Math.pow(10, n-1); // for i = 0
for (int i = 0; i < n; i++) {
System.out.println(sum*pow);
pow /= 10;
}

Minimum number of substitutions to reach string: 01010101 ... 01 or 10101010 ... 10

Given a binary string, that is it contains only 0s and 1s (number of zeros equals the number of ones) We need to make this string a sequence of alternate characters by swapping some of the bits, our goal is to minimize the number swaps.
For example, for the string "00011011" the minimum number of swaps is 2, one way to do it is:
1) swap the bits : 00011011 --->> 00010111
2) swap the bits(after the first swap) : 00010111 --->> 01010101
Note that if we are given the string "00101011" we can turn it into an alternate string starting with 0 (that requires 3 swaps) and also into alternate string starting with 1 ( that requires one swap - the first and the last bits ).
So the minimum in this case is one swap.
The end goal is to return the minimum number of swaps for a given string of ones and zeros. What is the most efficient way to solve it?
What you are looking for is called the Levenshtein distance. It is a bit more complex since it works on all type of String not just bitstrings but based on the implementation you should be able to develop your own fitting solution. Here is an java implementation I found on Wikibooks:
public static int computeLevenshteinDistance(CharSequence lhs, CharSequence rhs) {
int[][] distance = new int[lhs.length() + 1][rhs.length() + 1];
for (int i = 0; i <= lhs.length(); i++)
distance[i][0] = i;
for (int j = 1; j <= rhs.length(); j++)
distance[0][j] = j;
for (int i = 1; i <= lhs.length(); i++)
for (int j = 1; j <= rhs.length(); j++)
distance[i][j] = minimum(
distance[i - 1][j] + 1,
distance[i][j - 1] + 1,
distance[i - 1][j - 1] + ((lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1));
return distance[lhs.length()][rhs.length()];
}

Problems with Binary to Decimal conversion in java (arrays)

My assignment is to convert binary to decimal in a JLabel array without using pre-written methods (there's no user input). I have the right idea but for some reason the output is always a little bit off. I've gone through it countless times but I can't find anything wrong with my algorithm and I'm very confused as to why it doesn't produce the correct answer. I'd be very grateful if someone could help me out. Thanks!
Side note: I've read similar discussion threads regarding binary to decimal conversions but I don't understand how to do it with arrays.
Here is a snippet of my code:
private void convert()
{
int[] digit = new int[8]; //temporary storage array
int count = 0;
for(int x = 0; x < digit.length; x++)
{
digit[x] = Integer.parseInt(bits[x].getText()); //bits is the original array
count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x));
}
label.setText("" + count);
}
You are following the binary number from left to right but are grabbing the wrong digit. You want the same digit but to multiply by the right power of two - first index being +n*128 and not +n*1
int count = 0;
for(int i = 0; i < bits.length; i++) {
count += Integer.parseInt(bits[i].getText()) * Math.pow(2, bits.length - i - 1);
}
Obviously there is a bug in your snippet.
You set the digit[x], but not set the digit[length - 1 - x].
for example, x = 0, you set the digit[0], but not set digit[7].
So there will be an error when you want use the digit[length - 1 -x] here :
count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x));
This the correct code here:
private void convert()
{
int count = 0, length = 8;
for(int i = 0; i < length; count += Integer.parseInt(bits[i].getText()) * (1 << (length - 1 - i)), i++);
label.setText("" + count);
}
Have not test the code. But I think it will work.

Add 0's to the end of an integer

for(i=0; i<array.length; i++){
sum = 4 * 5;
}
What I'm trying to do is add ((array.length - 1) - i) 0's to the value of sum. For this example assume array length is 3. sum equals 20. So for the first iteration of the loop i want to add ((3 - 1) - 0) 0's to the value of sum, so sum would be 2000. The next iteration would be ((3 - 1) - 1) 0's. so sum would equal 200 and so on. I hope what I am trying to achieve is clear.
So my questions are:
Is it possible to just shift an int to add extra digits? My search thus far suggests it is not.
If not, how can i achieve my desired goal?
Thankyou for reading my question and any help would be greatly apreciated.
You can just multiply it by 10 however many times.
200 * 10 = 2000
etc
So in your case, you'd have to use a for loop until the end of the array and multiply sum every iteration. Be careful though, because the max value of an int is 2^31, so it of surpasses that, it will roll back to 0
You can add n zeroes to the end of a number, sum by multiplying sum by 10 * n.
int sum = 20;
for (int i = 0; i < ary.length; ++i) {
int zeroesToAdd = ary.length - 1 - i
sum *= (zeroesToAdd > 0) ? zeroesToAdd * 10 : 1
}
System.out.println("Sum after loop: " + sum);
for(int i=array.length; i>0; i--){
sum = 20;
for(int j=0; j < (i - 1); j++)
{
sum *= 10;
}
}
Use inner loop to multiply by 10 the number of times i is for that iteration. You would need to reset sum in your outer loop each time.
You will want to check your for-loop condition: i>array.length. Since i starts at 0, this loop will not run unless the array's length is also 0 (an empty array). The correct condition is i < array.length.
This "shift" you want can be achieved by creating a temporary variable inside the loop that is equal to the sum times 10i. In Java's Math library, there is a pow(a,b) function that computes ab. With that in mind, what you want is something like this:
int oldSum = 4 * 5;
for (int i = 0; i < array.length; i++) {
int newSum = oldSum * Math.pow(10,i);
}
Multiply by 10 instead, and use < (not >) like
int sum = 20;
int[] array = { 1, 2, 3 };
for (int i = 0; i < array.length; i++) {
int powSum = sum;
for (int j = array.length - 1; j > i; j--) {
powSum *= 10;
}
System.out.println(powSum);
}
Output is (as requested)
2000
200
20
For array of length = n; you will end up adding (n - 1) + (n - 2) + ... + 2 + 1 + 0 zeros for i = 0, 1, ... n-2, n-1 respectively.
Therefore, number of zeros to append (z) = n * (n-1) / 2
So the answer is sum * (10 ^ z)
[EDIT]
The above can be used to find the answer after N iteration. (I miss read the question)
int n = array.length;
long sum = 20;
long pow = Math.pow(10, n-1); // for i = 0
for (int i = 0; i < n; i++) {
System.out.println(sum*pow);
pow /= 10;
}

Bin To Dec code explaination

T student, my teacher said that the codes are okay.. but she asked me that how come binary input 00101 becomes 5.0 dec.
i really need help. i dont know how to explain how 00101 bin becomes 5.0
i tried many calculations like.
5(chararraylength)-3(index)-1 * math.pow = 4
i cant get the last the number that makes my 4 into 5.o dec.
char[] charArray = binary.toCharArray();
double answer = 0;
for (double index = 0; index < charArray.length; index++){
if (charArray[(int)index] == '1') {
answer = answer + Math.pow(2.0, (charArray.length - index - 1));
You use Math.pow() which operates on doubles, this is therefore normal.
Either print (int) answer or use this instead:
final int size = charArray.length;
char c;
int answer = 0;
for (int index = size; index > 0; index++) {
if (charArray[index] == '1')
answer++;
answer <<= 1;
}
Also note that array indices are ints, so your index variable should be an int.
I'm not sure if I understand your question correctly, but here is the calculation the program makes:
00101 means
0*2^4 + 0*2^3 + 1*2^2 + 0* 2^1 + 1* 2^0
= 0*16 + 0*8 + 1*4 + 0*2 + 1*1 = 5
More details at Wikipedia Binary_number

Categories