I was curious how to muliply an array by a factor? Not each cell (t[0], t[1], etc) individually, but as a whole number. Ex: t[0] = 9 t[1] =2 t[2] = 5, t[] = 925. 925 times 3 =2775
Basically, I am receiving a value and converting from ASCII to Decimal(I have already done this). However, I want to multiply by it a factor of 3. Do I need to store the entire array as a string, and then use the multiply function?
The relevant code for this section
byte[] readBuf =(byte[]) msg.obj);
char x;
String readMessage = newString(readBuf,0,msg.arg1);
int[] t = new int[readMessage.length()];
for(int i = 0; i<readMessage.length(); i++)
{
x = readMessage.charAt(i);
int z = (int) x;//Array has been converted from ASCII into decimal values
t[i] = z;//Array has been populated with decimal values
//Confused about the next part, Convert back into string and then multiply string?
}
Why make extra variables for char and int, use space for tables and pass things from one variable to another when you can do it all in one line? From what i've understood this is all you need.
byte[] readBuf =(byte[]) msg.obj);
String readMessage = newString(readBuf,0,msg.arg1); //You create the string here
String final=""; //new string to be parsed
for(int i = 0; i<readMessage.length(); i++){
final+=""+(int)readMessage.charAt(i); // get the charAt(i) cast it to int and give it to the string
}
return Integer.parseInt(final)*factor; //return the int multiplied by 3
Edit: Use Double.parseDouble(readMessage) to convert it to decimal
ASCII characters are only Integer numbers
I'm not sure if I understand the format of your input string. Does this example solve your problems?
public static void main(String args[]) throws Exception {
String input = "925";
int parsed = Integer.parseInt(input);
parsed *= 3;
System.out.println(parsed); // prints 2775
}
Your ask is not clear, I try to understand: you have a String in an array where the zero index is the most significative position and the last is the less significative position. So, if you have 123, the situation is t[0]=1, t[1]=2, t[2]=3.
If it's correct, then you say you want to rebuild the number (in my example 123 and return that multiplyed by a factor, i.e. 3). So return 369.
Here's my solution assuming that the resulting number will be lower than MAXINT.
I also mantain your code as is, and return the result multiplyed by a factor in value "factor" (int).
byte[] readBuf =(byte[]) msg.obj);
char x;
String readMessage = newString(readBuf,0,msg.arg1);
int[] t = new int[readMessage.length()];
String final="";
for(int i = 0; i<readMessage.length(); i++)
{
x = readMessage.charAt(i);
int z = (int) x;//Array has been converted from ASCII into decimal values
t[i] = z;//Array has been populated with decimal values
final+=""+t[i]; // add to String the char in position i.
//Confused about the next part, Convert back into string and then multiply string?
}
return Integer.parseInt(final)*factor;
Related
I have an array of integer 1s and 0s (possibly need to get converted to byte type?). I have used [an online ASCII to binary generator][1] to get the equivalent binary of this 6 digit letter sequence:
abcdef should equal 011000010110001001100011011001000110010101100110 in binary.
My array is set up as int[] curCheckArr = new int[48]; and my string is basically just using a StringBuilder to build the same ints as strings, and calling toString() - so I have access to the code as a string or an array.
I have tried a few different methods, all of which crash the browser, including:
StringBuilder curCheckAlphaSB = new StringBuilder(); // Some place to store the chars
Arrays.stream( // Create a Stream
curCheckString.split("(?<=\\G.{8})") // Splits the input string into 8-char-sections (Since a char has 8 bits = 1 byte)
).forEach(s -> // Go through each 8-char-section...
curCheckAlphaSB.append((char) Integer.parseInt(s, 2)) // ...and turn it into an int and then to a char
);
String curAlpha = curCheckAlphaSB.toString();
and
String curAlpha = "";
for (int b = 0; b < curCheckString.length()/8; b++) {
int a = Integer.parseInt(curAlpha.substring(8*b,(b+1)*8),2);
curAlpha += (char)(a);
}
How can I most efficiently convert these 48 1s and 0s to a six digit alpha character sequence?
Assuming each character is represented by precisely one byte you can iterate over the input with Integer.parseInt() (because byte value in the input is potentially unsigned):
String input = "011000010110001001100011011001000110010101100110";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i += 8) {
int c = Integer.parseInt(input.substring(i, i + 8), 2);
sb.append((char) c);
}
System.out.println(sb); // abcdef
Using a regex is probably the slowest part of these. Using a pre-compiled regex would help, but substring is faster. Not creating any Strings except the result would be faster. e.g. use StringBuilder instead of += for String.
Im currently working on a QRCode scanne and have come to a point where I've been stuck at for a while.
What I have so far is a String of 1s and 0s such as "100010100101....". What I wanted to do next ist turn this String into Bytes by always seperating 8 Bits.
With these Bytes I now want to decode them into text with this "ISO8859_1" Standart.
My Problem is the following: my results are way of what I want. This is my code:
for(int i = 0; i <= numberOfInt; i++){
String character = "";
for(int j = 0;j < 8; j++){
boolean bool = tResult.remove(0); //tResult is a List of 1s & 0s
if(bool){
character = character + '1';
}else{
character = character + '0';
}
}
allcharacter[byteCounter] = (byte)Integer.parseInt(character,2);//I think this Line is where the mistake is.
byteCounter++; //Variable that counts where to put the next bit
}
String endresult ="";
try {
endresult = new String(allcharacter,"ISO8859_1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return endresult;
What I think is that, the cast to (byte) doesn't work the way I understand it and therefore different bytes are saved into the array.
Thanks for any help.
You can use the substring method of the String class to get the first 8 characters and then convert those 8 characters (treat them as bits) to a character (which is also 8 bits). Instead of parsing each character as an integer, and then casting it to a byte, you should check each character and multiply a byte value by 2 for each time you hit a 1. That way, you will get a value between 0-255 for each byte, which should give you a valid character.
Also you might want to check the Byte class and its methods, it probably has a method that already does this.
Edit: There you go.
Edit 2: Also this question may answer why your int to byte casting does not give you the result you thought it would.
Okay, I rarely work with bytes, so in that aspect I am useless. However, I have converted binary to string many times. The logic behind it is converting the binary string to a decimal int, then from int to char, then from char to string. Here is how I do that.
String list = "100111000110000111010011" //24 random binary digits for example
String output = "";
char letter = '';
int ascii = 0;
//Repeat while there is still something to read.
for(int i = 0; i < list.length(); i+=8){
String temp = list.substring(i,i+8); //1 character in binary.
for(int j = temp.length()-1; j >= 0; j--) //Convert binary to decimal
if(temp.charAt(j) == '1')
ascii += (int)Math.pow(2,j);
letter = (char)ascii; //Sets the char letter to it's corresponding ascii value
output = output + Character.toString(letter); //Adds the letter to the string
ascii = 0; //resets ascii
}
System.out.println(output); //outputs the converted string
I hope that you found this helpful!
I've the below program.
public class swapping {
public static void main(String[] args) {
String num = "31254";
int max = Integer.MIN_VALUE, maxIndex = 0;
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) > max) {
max = num.charAt(i);
maxIndex = i;
}
}
swap(num, num.charAt(0), maxIndex);
}
private static void swap(String num, char charAt, int maxIndex) {
System.out.println("number is " + num + " Initial char is " + charAt
+ " Maximum is " + maxIndex);
char t = charAt;
char s = num.charAt(maxIndex);
System.out.println("numbers:" + t + " " + s);
char temp = t;
t = s;
s = temp;
System.out.println("Final string after swap is " + num);
}
}
here my aim is to get the maximum number in the string to be swapped with the first number in the string. i.e. I want to convert 31254 to 51234. But i'm unable to know how to do this.
number is 31254 Initial char is 3 Maximum is 3
numbers:3 5
Final string after swap is 31254
Here the swapping is not getting done, the previous number is getting printed. please let me know how to print the desired output.
Thanks
Pay attention what you are passing to the method.
You are passing the actual character in the first and max position: 3 and 5 in this case.
But then, after you print them, you call:
char t = num.charAt(initial);
char s = num.charAt(max);
charAt expects the index of the character in the string. The index should be an integer, but you are passing it a char value (the character 3 and the character 5).
Now, in Java, characters are considered numbers between 0 and 65535 - the unicode value of the character. So it allows you to pass a character where you should have passed an integer. The unicode value of 3 is 51, and for 5 it's 53. So you are actually telling it "give me the character in the string num which is in position 51".
This is not what you intended.
Instead of doing that, you should make the method accept the index of the first character and the index of the max character. Then, using charAt will be correct. But pay attention to also use charAt for your print at the beginning.
private static void swap(String num, int initialIndex, int maxIndex) {
...
}
Your other problem is that you are not actually swapping the characters inside the string.
What you did was swap the variables that contain the two characters, t and s. So now t contains what s contained, and s contains what t contained.
However, this has no bearing on the original string num. You have not done anything with the string itself.
One thing to remember is that in Java, you cannot change a string. It's immutable. If you have a string object, Java doesn't give you any way to change things inside it. It only lets you read parts of it, not write.
What you can do is assign a new string value to num. In this new string, you will put the value of the max character in the 0 position, and put the value of what was in the first position, in the max character position. And you'll copy all the other characters in the same positions where they were.
So you'll need to create a temporary string, loop on the original string character by character, and in each position, ask yourself "what character should I add to my new string at this round?". And then add that character to the string with a + operator.
Finally, assign the new, temporary string to num.
(Note: there are more efficient ways to do this in Java, like using a StringBuffer or StringBuilder, but I get the impression that you are not there yet in your studies of Java).
try the below program.
String num = "31254";
int maxIndex = 0;
char maxString = num.charAt(0);
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) > maxString) {
maxString = num.charAt(i);
maxIndex = i;
}
}
System.out.println(maxString);
System.out.println(maxIndex);
String str1 = num.substring(1,maxIndex);
String str2 = num.substring(maxIndex+1,num.length());
String str3 = num.charAt(maxIndex)+str1+num.charAt(0)+str2;
System.out.println(str3);
Initial is a char. charAt use an integer, so the char will converted in the acii code of 3 wich is 51. So your line is equals to `num.charAt(51) and that is out of range.
So hyou have to change the signature of your mathod to private static void swap(String num, int initial, int max)
Here's how I would do it in just 3 lines. Note that for digits, chars are 1 byte each.
byte[] array = number.getBytes();
Arrays.sort(array);
number = number.replaceFirst("(.)(.*?)(" + (array[array.length - 1] - '0') + ")", "$3$2$1");
Not only is this code quite terse - using regex to perform the swap in one statement - it also automatically handles the edge case of the largest digit being at the start (in which case no match/replacement will be made).
Here's some test code:
String number = "31254";
byte[] array = number.getBytes();
Arrays.sort(array);
number = number.replaceFirst("(.)(.*?)(" + (array[array.length - 1] - '0') + ")", "$3$2$1");
System.out.println(number);
Output:
51234
I have no idea of why this code snippet produces the following output when I try to multiply 2 int values. This might be too dumb but I just dont get it. I have pasted the code and the output here
public static void main(String[] args) {
// TODO code application logic here
String numstring = "12122";
char[] numArray = numstring.toCharArray();
int num =0;
int index = 10;
int count = 0;
for(int i=numArray.length-1;i>=0;i--){
int ind = (int)(Math.pow(index,count));
System.out.print(numArray[i]+"*"+ind);
System.out.println(" prints as ----->"+numArray[i]*ind);
count++;
}
}
output:
2*1 prints as ----->50
2*10 prints as ----->500
1*100 prints as ----->4900
2*1000 prints as ----->50000
1*10000 prints as ----->490000
You're not multiplying two ints. Your multiply an int, ind, with a char, '2', whose ASCII value is 50 (at least in the first case). You could use an int[], or if you want to stick with the char[], you could do the following:
System.out.println(" prints as ----->"+ Character.getNumericValue(numArray[i]) * ind);
Characters are really integers under the hood, so for example, the character '2' has int value 50.
To see which integer corresponds to which character, check out the ascii table.
To do what you want, you should use Character.getNumericValue() method:
System.out.println(" prints as ----->"+Character.getNumericValue(numArray[i])*ind);
I'm trying to convert a string filled with 16 digits into an array of ints where each index holds the digit of its respective index in the string. I'm writing a program where I need to do math on individual ints in the string, but all of the methods I've tried don't seem to work. I can't split by a character, either, because the user is inputting the number.
Here's what I have tried.
//Directly converting from char to int
//(returns different values like 49 instead of 1?)
//I also tried converting to an array of char, which worked,
//but then when I converted
//the array of char to an array of ints, it still gave me weird numbers.
for (int count = 0; count <=15; count++)
{
intArray[count] = UserInput.charAt(count);
}
//Converting the string to an int and then using division to grab each digit,
//but it throws the following error (perhaps it's too long?):
// "java.lang.NumberFormatException: For input string: "1234567890123456""
int varX = Integer.parseInt(UserInput);
int varY = 1;
for (count=0; count<=15; count++)
{
intArray[count]= (varX / varY * 10);
}
Any idea what I should do?
how about this:
for (int count = 0; count < userInput.length; ++count)
intArray[count] = userInput.charAt(count)-'0';
I think that the thing that is a bit confusing here is that ints and chars can be interpited as eachother. The int value for the character '1' is actually 49.
Here is a solution:
for (int i = 0; i < 16; i++) {
intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}
The substring method returns a part of the string as another string, not a character, and this can be parsed to an int.
Some tips:
I changed <= 15 to < 16. This is the convetion and will tell you how many loop interations you will actually go throug (16)
I changed "count" to "i". Another convention...