Is there a better way to get bit[] from binary string
e.g.
Let say I want bits from index=3 up to length (len=5)
BinaryString = 10011000000000010000111110000001
Expected Result = 11000
This is what I have so far.
Method 1
public void getBits1(){
int idx = 3;
int len = 5;
String binary = new BigInteger("98010F81", 16).toString(2);
char[] bits = binary.toCharArray();
String result = "";
//check here: to make sure len is not out of bounds
if(len + idx > binary.length())
return; //error
for(int i=0; i<len; i++){
result = result + bits[idx];
idx++;
}
//original
System.out.println(binary);
//result
System.out.println(result);
}
Method 2
public void getBits2(){
int idx = 3;
int len = 5;
String binary = new BigInteger("98010F81", 16).toString(2);
String result = binary.substring(idx, len+idx);
//original
System.out.println(binary);
//result
System.out.println(result);
}
i think value.substring(int,int) do fine.
Related
I came across this interview question.
Write a program that accepts an array of integers and returns an integer whose digits consist of the numbers in that array?
For instance, if the array contains {1,2,3}, the method should return 123.
Thanks.
Currently I have this
public int transformArray(int [] numberArray){
for(int i=0; i<=numberArray.length;i++){
int number=number+number.CharAt(i);
}
}
You can concatenate each char to a string and convert it back to int:
public int transformArray(int [] numberArray){
String ans = "";
for(int i=0; i<=numberArray.length;i++){
ans = ans + numberArray[i];
}
return Integer.parseInt(ans)
}
Or multiply by 10 as David Conrad suggested
public int transformArray(int [] numberArray){
int ans = 0;
for(int i=0; i<=numberArray.length;i++){
ans = ans * 10;
ans = ans + numberArray[i];
}
return ans
}
Try something simple like:
int result = 0;
for (int i = 0; i<array.length; i++) {
result += array[i] * Math.pow(10, array.length - i - 1);
}
return result;
Use this:
public String getName() {
//create new ArrayList
ArrayList<Integer> numbers = new ArrayList<Integer>();
//add numbers
numbers.add(1);
numbers.add(9);
//for each element in the list, add the number
String s = "";
for(int i : numbers) {
s = s + i;
}
System.out.println("String: " + s);
return s;
}
The output of the method in this case:
String: 19
If you want the String s as an Integer use:
int i = Integer.parseInt(s)
I want to convert binary to decimals and characters like this:
11010 --> 1101 + 0(parity bit) -->decimals= 11 --> char ";"
10101 --> 1010 + 1 -->decimals= 5 --> char "5"
.
.
public class stringek {
String bitek = "1101010101001000001000001";
String[] bits;
String four;
char par;
int parity;
String digits;
int n = 0;
int b;
int kurens;
int decimalis;
int digit;
public stringek() {
this.kurens = 0;
bits = new String[200];
for (int i = 0; i < 25; i += 5) {
bits[n] = bitek.substring(i, i + 5);
n++;
}
for (int i = 0; i < n; ++i) {
int j = 0;
four = bits[i].substring(j, j + 4);
for (int p = 0; p < 4; ++p) {
b = Integer.parseInt(four.substring(p));
kurens += b;
}
par = bits[i].charAt(j+4);
//System.out.print(par);
parity = par-'0';
decimalis = Integer.parseInt(four, 2);
digit = decimalis + 48;
if ((kurens + parity) % 2 == 0) {
System.out.println("Binarys: "+four+"-"+par+" = "+"'"+(char)digit+"'"+" Decimalis:"+decimalis+" Parity <INVALID> ");
}
else{
System.out.println("Binarys: "+four+"-"+par+" = "+"'"+(char)digit+"'"+" Decimalis:"+decimalis+" Parity <VALID> ");
}
}
}
}
but my program results this:
Binarys: 1101-0 = '=' Decimalis:13 Parity <INVALID>
Binarys: 1010-1 = ':' Decimalis:10 Parity <VALID>
Binarys: 0010-0 = '2' Decimalis:2 Parity <INVALID>
Binarys: 0001-0 = '1' Decimalis:1 Parity <INVALID>
Binarys: 0000-1 = '0' Decimalis:0 Parity <VALID>
Can anyone help me to resolve? I have to say cause in my case all Parity is VALID, but I don't know why here some Parity is Invalid (I know cause the results from if give me this results, but I want to know how to resolve to be VALID when is valid and INVALID when is really invalid). thanks
public String[] splitStringEvery(String s, int interval) {
int arrayLength = (int) Math.ceil(((s.length() / (double)interval)));
String[] result = new String[arrayLength];
int j = 0;
int lastIndex = result.length - 1;
for (int i = 0; i < lastIndex; i++) {
result[i] = s.substring(j, j + interval);
j += interval;
} //Add the last bit
result[lastIndex] = s.substring(j);
return result;
}
You wouldn't use String.split() or a StringTokenizer
Use a for loop that increments by 5, checking against length of your string
Use String.substring() to extract the 5 character strings.
To compute the length of the target array you need, you'll need to divide your string length by 5. A Better idea is to use a List<String>.
Use the Guava Libraries Splitter object, specifically the fixedLength(...) method which does exactly what you're trying to do.
Splitter splitter = Splitter.fixedLength(5);
Iterable<String> tokens= splitter.split(myVeryLongString);
I have bytes in a byte array. I need to store the bit value of each byte in an integer array .
For example ,
the byte array is
byte HexToBin[] = {(byte)0x9A, (byte)0xFF,(byte) 0x05,(byte) 0x16};
then the integer array should have
a = [10011010111111110000010100010110]
I have tried the following code, where i was able to print the binary value of each byte (s2) but i couldnot store in integer array allBits.
byte hexToBin[] = {(byte)0x9A, (byte)0xFF,(byte) 0x05,(byte) 0x16};
int[] allBits = new int[32];
int a =0;
for (int i =0; i < hexToBin.length ; i++)
{
byte eachByte = hexToBin[i];
String s2 = String.format("%8s", Integer.toBinaryString((eachByte)& 0xFF)).replace(' ', '0');
System.out.println(s2);
char [] totalCharArr = s2.toCharArray();
for (int k=0; k <8; k++)
{
allBits[k+a]= totalCharArr[k];
}
a= a+8;
}
for (int b=0; b<32;b++)
{
System.out.print(allBits[b]);
}
The output of above code is
10011010
11111111
00000101
00010110
4948484949484948494949494949494948484848484948494848484948494948
The integer array does not have the binary value.
////////////////////////////////////////////////////////////////////////////////////////////////////
Thank you for the help
The Corrected code is
byte hexToBin[] = {(byte)0x9A, (byte)0xBF,(byte) 0x05,(byte) 0x16};
int[] allBits = new int[32]; // no of bits is determined by the license code
for (int n =0; n<hexToBin.length; n++)
{
//Use ints to avoid any possible confusion due to signed byte values
int sourceByte = 0xFF &(int)hexToBin[n];//convert byte to unsigned int
int mask = 0x80;
for (int i=0; i<8; i++)
{
int maskResult = sourceByte & mask; // Extract the single bit
if (maskResult>0) {
allBits[8*n + i] = 1;
}
else {
allBits[8*n + i] = 0; // Unnecessary since array is initiated to zero but good documentation
}
mask = mask >> 1;
}
}
for (int k= 0; k<32; k++)
{
System.out.print(allBits[k]);
}
Assumed to be inside a loop of n = 0 to 3
// Use ints to avoid any possible confusion due to signed byte values
int sourceByte = 0xFF & (int)(hexToBin[n]); // Convert byte to unsigned int
int mask = 0x80;
for (int i = 0; i < 8; i++) {
int maskResult = sourceByte & mask; // Extract the single bit
if (maskResult != 0) {
allBits[8*n + i] = 1;
}
else {
allBits[8*n + 1] = 0; // Unnecessary since array is inited to zero but good documention
}
mask = mask >> 1;
}
Try System.out.print((char)allBits[b]); or try declaring allBits as char[], not int[].
I've been stuck on this problem for two hours now. Basically I need to reverse a string (which I've done no problem), then swap every nth letter (which is where im stuck).
Here is what I have so far:
public class StringMethods {
public static void main(String[] args) {
String s = "Hey there";
int n = 2;
System.out.println(reverseString(s));
System.out.println(reverseStringChallenge(s, n));
}
private static String reverseString(String s) {
String reversed = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i);
}
return reversed;
}
private static String reverseStringChallenge(String s, int n) {
String reversed = "";
String swapped = "";
for (int i = s.length() - 1; i >= 0; i--) {
reversed = reversed + s.charAt(i); // normal reverse
}
char [] charArray = reversed.toCharArray(); //Strings are immutable, convert string to char array
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0) {
//this is where im stuck
}
}
return swapped;
}
}
I know that strings are immutable in java so I need to convert the reversed string into a char array, and then loop through the array but not sure what to do here.
Any advice would be really appreciated. its doing my head in.
Edit: sorry what I mean by swap every nth letter is that say n = 2. then every second letter gets swapped with its previous one.
You didn't clarify the swap logic, but how about something like this:
for(int i = n; i < charArray.length; i += n) {
char a = charArray[i-n];
char b = charArray[n];
charArray[i-n] = b;
charArray[n] = a;
}
Here's a basic swap
int n = 1;
int n1 = 2;
int temp = n; // variable to hold n value
n = n2; // make n = n2
n2 = temp; // make n2 = n
// now n = 2
// and n2 = 1
Not really sure from your question what it is you're trying to do, so I can't really give a definite answer
If you are swapping the current char with the next char you could do something like:
private static String reverseStringChallenge(String s, int n)
{
String reversed = StringUitls.reverse(s);
StringBuilder sb = new StringBuilder();
char [] charArray = reversed.toCharArray();
for(int i = 0; i < charArray.length; i++) {
if(i%n == 0)
{
sb.append(charArray[i+1]).append(charArray[i]);
i++;
}else{
sb.append(charArray[i]);
}
}
return sb.toString();
}
I'm excuse null and out of bound checks =) good luck
I am working on the RSA algorithm and have made some progress but it is not working. I have the following code.
public class RSA
{
public static void main(String args[])
{
String plainText = "ITS ALL GREEK TO ME";//temp local plaintext ignoring parameter
plainText = plainText.toUpperCase();
plainText = plainText.replaceAll("\\s","");
System.out.println(plainText);
String cipherText = "";
int p = 47; //has been provided
int q = 59; //has been provided
int d = 157; //has been provided
int n = p * q;//calculate n
int w = (p - 1)*(q - 1);// calculate W
int c = 0;//we will compute this = cipher variable
int m = 920;//hardcoded for now
int e = 17;//hardcoded for now
//start of euclids
ArrayList<Integer> remainderlist=new ArrayList<Integer>();//array list to hold the remainder values in euclids algorithm from the quotient
remainderlist.add(w);// step 1 of euclids algorithm starting with value of w as above
remainderlist.add(d);// step 2 of euclids algorithm to add value of d
int remainderposition1 = 0;
int remainderposition2 = 1;
int quotient = 0;
int remainder = 0;
while (remainderlist.get(remainderposition1)%(remainderlist.get(remainderposition2))>0){
quotient = remainderlist.get(remainderposition1)/remainderlist.get(remainderposition2);
remainder = remainderlist.get(remainderposition1)%remainderlist.get(remainderposition2);
remainderlist.add(remainder);
System.out.println("Q: " +quotient);
System.out.println("R: " +remainder);
System.out.println("");
remainderposition1++;
remainderposition2++;
}
//start string processing
//loop etc
if (plainText.length()%2!=0)
{
plainText = plainText + " ";
}
for (int i = 0, i < plainText.length(); i = i+2)
{
char plTChar1 = plainText.CharAt(i);
char plTChar2 = plainText.CharAt(i + 1);
// Convert the character into an ASCII table value.
int asciiValue1 = (int) plTChar1;
int asciiValue2 = (int) plTChar2;
String numStr1 = asciiValue1.parseInt;
String numStr2 = asciiValue2.parseInt;
if (numStr.length() < 2)
{
numStr = "0" + numStr;
}
String fullNum = numStr1 + numStr2;
int m = Integer.parse(fullNum);
//start of encryption algorithm
String binarystring = Integer.toBinaryString(e);// step 1
System.out.println(binarystring);
c = 1; // step 2 of the encryption algorithm - notes
for (int i = 0; i<binarystring.length();i++)
{
c = (c*c)%n;// setp 3a
System.out.println(binarystring.charAt(i));
// step 3b notes
if (binarystring.charAt(i)=='1') {
c = (c*m)%n;
}
}
System.out.println("Cipher"+c);
}
When I build the file I get errors on the line for (int i = 0, i < plainText.length(); i = i+2) saying that quotation marks are expected and that it is an illegal start to an expression. I'm lost
You have a comma instead of a semi-colon.
for (int i = 0, i < plainText.length(); i = i+2)
Should be
for (int i = 0; i < plainText.length(); i = i+2)
Often the smallest syntax error will confuse you for hours!