replacing Least Significant bits - java

i want to replace Least significant bits with the given array...
1st input
01001100
00001000
10101010
01010100
11110110
2nd input
0
1
1
1
0
output
01001100
00001001
10101011
01010101
11110110

try this (using java 7)
int [] i = {0b01001100,
0b00001000,
0b10101010,
0b01010100,
0b11110110 };
int [] j = {0b0,
0b1,
0b1,
0b1,
0b0 };
for (int k = 0; k < i.length ; ++k){
i[k] = (i[k] >> 1) << 1; // this sets the last bit to zero
i[k] = i[k] | j[k]; // Now you can OR to get replace with the proper value
}
for(int k : i)
System.out.printf("%8s\n",Integer.toBinaryString(k));
System.out.println("----------");

Related

Bitwise operations in java

what does this piece of code mean ...Can anyone explain how does this work..
sum += (i & (1<<j)) != 0 ? n[j] : 0;
full code:
int max = (1 << N)-1;
//System.err.println(max);
String res = "No";
for (int i = 0; i <= max; i++)
{
long sum = 0;
for (int j = 0; j < N; j++)
{
sum += (i & (1<<j)) != 0 ? n[j] : 0;
}
//System.err.println(i + " " + sum);
if(sum == m){
res = "Yes";
break;
}
Let's say that a = 0011 1100
So with the Binary Left Shift Operator (<<). The left operands value is moved left by the number of bits specified by the right operand.
A << 2 will give 240 which is 1111 0000
So in your code you have a loop for i and a loop for j
And this line
sum += (i & (1<<j)) != 0 ? n[j] : 0;
So for your second iteration of i = 2 and first iteration of j = 1
First the left shift operator will shift left all bits one position, resulting in 0000 0001 << 1 = 0000 0010 (or 2)
then you have a binary and comparison which will be i (0000 0010 in binary) & (0000 0010) = 0000 0010 (or 2)
And this and result will be asked if it's distinct of zero. If this result it's true then sum will be increased by the number in the n[j] array position, else will not be increased.
Java has a shortened version of an if else command. The use of it is very easy, once you understand it.
It’s written:
x ? y : z;
Here the question mark and the colon will take the place of the commands if and else.
This means:
condition ? inCaseOfTrue : elseCase;
With this code i & (1 << j) you get jth bit of i in binary representation. And if it equals 1 then you add n[j] to sum.
The full code shows you calculate all possible sums with selecting some elememts of array n;

Find Kth digit number after n changes

There is a changing rule that, 0 -> 01, 1 -> 10. For example, after the change, 10 is 1001.
Assume that the input is 0, after n changes of such rule, what is the Kth digit?
I can only come with the brutal solution, which is as followings. However I believe there exist better solutions, can anyone come up with some new ideas?
public char lalala(int n, int k) {
String str = "0";
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < str.length; j++) {
if (str.charAt(j) == '0') {
sb.append("01");
} else {
sb.append("10");
}
}
str = sb.toString();
}
return str.charAt(k);
}
So your generated string will look like
0110100110010110....
Now lets write this numbers vertically and lets print binary representation of position of each digit
value|position -> position binary
-----+---------------------------
0 | 0 -> 0000
1 | 1 -> 0001
1 | 2 -> 0010
0 | 3 -> 0011
1 | 4 -> 0100
0 | 5 -> 0101
0 | 6 -> 0110
1 | 7 -> 0111
. . ....
. . ....
If you take closer look you will see that:
if number of 1 in binary representation of position is even value is 0
if number of 1 in binary representation of position is odd value is 1
which means that
0001, 0010, 0100, 0111 contains odd number of 1 value will be 1.
In other words value is equal of number of ones modulo 2.
Using this fact you can create code which will convert your n to string representing its binary form, sum all ones, and check if it is odd or even.
Code converting n to value can look like this
public static int value(int n) {
String binary = Integer.toBinaryString(n);
return binary.chars().map(e -> e == '1' ? 1 : 0).sum() % 2;
}
(little longer version if you are not familiar with streams introduced in Java 8)
public static int value(Integer n) {
String binary = Integer.toBinaryString(n);
int count = 0;
for (char ch : binary.toCharArray())
if (ch == '1') count ++;
return count % 2;
}
and when you use it like
for (int i = 0; i < 20; i++)
System.out.print(value(i));
you will get as output 01101001100101101001 which seems correct.

Incrementing Char Issue (Hex)

I'm currently using a char as a counter in a char[]. An example of the problem I'm having is below:
char counter = 0x00;
for (int i = 0; i < 15; i++){
counter++;
}
This seemed to work well until I discovered that when i = 10, counter was assigned 0x10 and not 0x0A.
How can I increment the char to contain the hex value and not the decimal value?
Any suggestions or advice would be great!
The counter is assigned the correct value, you just need to convert it into hex form.
char counter = 0x00;
for (int i = 0; i < 15; i++){
counter++;
System.out.println(Integer.toHexString((int) counter);
}
Running this prints out 1 - f on single lines.
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
There's no decimal or hex value, there's only an integer value. The decimal and hex are just formats. When i is 0, counter gets a value of 1, when i is 1, counter becomes 2. When i is 10, counter becomes 11. I have expressed all values here in decimal format.
Try this:
int i = 7023;
System.out.println(Integer.toString(i, 16).toUpperCase());
System.out.println(Integer.toHexString(i).toUpperCase());

trying to subtract binary numbers with java program small error

im making a simple add and subtract binary calculator. i got it to take in a number and convert it into binary number, and i even got it to add the numbers. When i try and get it to subtract it doesnt work. i get a weird output. heres the piece of the code.
int [ ] subtarctBin = new int [16];
int carryX = 0;
for (int i = 0; i < 16; i++)
{
subtarctBin[i] = 0;
}
for (int i = 15; i >= 0; i--)
{
int subtract = resultBinA[i] - resultBinB[i] - carryX;
subtarctBin[i] = subtract % 2;
carryX = subtract / 2;
}
System.out.println("");
System.out.print("DIF:");
for(int i=0; i<16; i++)
{
System.out.print(subtarctBin[i]);
}
}
In addition to #Ken Y-N's answer, I find that in this statement, you are subtracting the first digit from the second along with the carryX.
int subtract = resultBinA[i] - resultBinB[i] - carryX;
I think you should ensure that the first number is the bigger of the two( i.e. resultBinB > resultBinA) and then the subtraction should go like this instead:
int subtract = (resultBinB[i] + carryX) - resultBinA[i];
Assuming that resultBinA and resultBinB contain the binary numbers, the problem is here:
subtarctBin[i] = subtract % 2;
According to the Java documentation, the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. So, when subtract equals -1, subtract % 2 also equals -1, so subtarctBin[i] will be -1 too, which is not what you want.
Furthermore, subtract / 2 will yield 0 when subtract equals -1, as Integer division rounds toward 0, as noted here.
Now, to solve your problem, build up this table:
resultBinA resultBinB carryX subtract required subtarctBin required new carryX
0 0 0 0 0 0
0 0 1 -1 1 1
0 1 0 -1 1 1
0 1 1 -2 0 1
1 0 0 1 1 0
1 0 1 0 0 0
1 1 0 0 0 0
1 1 1 -1 1 1
So, we can see, I hope, that:
subtarctBin[i] = (subtract + 2) % 2;
carryX = (subtract < 0 ? 1 : 0);
Gives you the results you require.
Try
if ((resultBinA[i] - resultBinB[i]) < 0 ){
int k = i-1;
while (resultBinA[k] != 1){
resultBinA[k] = 1;
k--;
}
resultBinA[k] = 0;
subract = 1;
}
else{
subract = (resultBinA[i] - resultBinB[i]);
}
I can give you a small hack.
Try to write a function to subtract a binary number by 1.
Then, make another function to check if a binary number is equal to 0 (basically, if we have a String like "010100" we need to check if each character is 0).
In your main function, keep subtracting until one of your numbers is 0. Return whichever is not 0. (Or return 0 if both numbers are 0.)
public String sub(String bin2){
while(!iszero(bin1) && !iszero(bin2)){
bin1 = subby1(bin1);
bin2 = subby1(bin2);
}
if(!iszero(bin1))
return bin1;
else
return bin2;
}
private String subby1(String bin){
int index = bin.length()-1;
while(bin.charAt(index) != '1'){
index--;
}
char[] c = bin.toCharArray();
c[index] = '0';
for(int x = bin.length()-1; x >= index + 1; x--){
c[x] = '1';
}
return String.valueOf(c);
}
private boolean iszero(String bin){
for(int x = 0; x < bin.length(); x++)
if(bin.charAt(x) == '1')
return false;
return true;
}
}

Specify number of bits in a String represetation of a binary number

I am trying to write a algorithm that will print a powerset of a given set of numbers. I did that with a loop that goes from zero to 2^length of my set. I convert the index i to binary, and whenever there is a one, I print that number. However, since the string does not have any preceding zeros, I am not getting the right output.
For example, if I have a set of three numbers: {2, 3, 4}, when i is 3, I want the string to be "011", but instead it is "11" and I'm getting an output of 2, 3 instead of 3, 4.
Here is my code:
public static void powerset (int[] A){
double powerSetLength = Math.pow(2, A.length);
for (int i=0; i<powerSetLength; i++){
String bin = Integer.toBinaryString(i);
System.out.println ("\nbin: " + bin);
for (int j=0; j<bin.length(); j++){
if (bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
System.out.println();
}
Here is the output that I am getting:
9 7 2
bin: 0
bin: 1
9
bin: 10
9
bin: 11
9 7
bin: 100
9
bin: 101
9 2
bin: 110
9 7
bin: 111
9 7 2
Here is an example of the output that I would like to get:
9 7 2
bin 001
2
I would like to know if there is a way to convert an integer to binary with a specified number of bits so that I can get this output.
One easy way to deal with this problem is assuming that if a digit is missing in the representation, then its value is zero. You can do it like this:
// The number of digits you want is A.length
for (int j=0; j < A.length ; j++) {
// If j is above length, it's the same as if bin[j] were zero
if (j < b.length() && bin.charAt(j)=='1')
System.out.print(A[j] + " ");
}
}
Of course if you can assume that A.length < 64 (which you should be able to assume if you want your program to finish printing in under a year) you could use long to represent your number, and bit operations to check if a bit is set or not:
int len = A.length;
for (long mask = 0 ; mask != (1L << len) ; mask++) {
for (int i = 0 ; i != len ; i++) {
if ((mask & (1L << i)) != 0) {
System.out.print(A[j] + " ");
}
}
System.out.print();
}
String padded = String.format("%03d", somenumber);
or
System.out.printf("%03d", somenumber);
Would each pad to three digits (the 3 in the format specifier). You could additionally build the specifier programatically based on length you need:
String.format("%0" + n + "d", somenumber)
But this is unnecessary if you just need to know if bit N is set. You could just as easily do this:
if ((value & (1L << n)) != 0) { }
Where value is the number, and n is the ordinal of the bit you want. This logically ands the bit in question with the value - if it's set, the result is non-zero, and the if is true. If it is not set, the result is zero, and the if is false.

Categories

Resources