Skip to content

Instantly share code, notes, and snippets.

@aravindc26
Created August 18, 2012 15:01
Show Gist options
  • Save aravindc26/3387297 to your computer and use it in GitHub Desktop.
Save aravindc26/3387297 to your computer and use it in GitHub Desktop.
invertbit
package com.adp.invertbit;
public class InvertBit {
public char invertBit(char inputChar, int position, int noOfPositions) {
//Write your code here
int rem = (char)inputChar; //the reminder in each stage of division
byte[] charArr = new byte[8]; //storing the bit representation
int i = 7;
//conversion of char(int) to array of bin numbers
while(!(rem == 0) && (i !=0)) {
if(rem % 2 == 0) {
charArr[i] = 0;
}
else {
charArr[i] = 1;
}
rem = rem/2;
--i;
}
for(i = 0; i<=7; i++){
System.out.println(charArr[i]);}
//inverting the bits
for(i = position-1; i < (position+noOfPositions-1); i++) {
if (charArr[i] == 0) {
charArr[i] = 1;
}
else{
charArr[i] = 0;
}
}
System.out.println("invert");
for(i = 0; i<=7; i++){
System.out.println(charArr[i]);}
// converting back to int
int resultInt = 0;
i = 0;
int j;
for(i = 0, j = 7; i < 7; i++, j--){
resultInt += charArr[j] * java.lang.Math.pow(2,i);
}
char resultChar = (char) resultInt;
return resultChar;
}
public static void main(String ar[]) {
char x = 'J';
int p = 3, n = 5;
char newChar =new InvertBit().invertBit(x, p, n);
System.out.println("\n\n New Character :"+ newChar);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment