I need for my app this int[] format as I wrote in the title.
I'm fetching the value out of a HashMap which is filled out of an XML file with this format [00, 00, 00, 00], but I need it for every int with 0xin front.
I tried to "convert" it via a for-loop:
for(int i = 0; i < value.length; i++){
value[i] = "0x" + value[i];
}
but I cant convert from String to int this way.
Then I tried to change it directly in the XML file, but then my app crashes with an NPE.
Now I want to know if there is a solution to my problem.
EDIT:
For further explanation:
I tried this before, but it did not work:
public int[] getValue(Map map, String key) {
Map keyMap = map;
int[] value = {};
#SuppressWarnings("rawtypes")
Iterator iter = keyMap.entrySet().iterator();
while (iter.hasNext()) {
#SuppressWarnings("rawtypes")
Map.Entry mEntry = (Map.Entry) iter.next();
if (mEntry.getKey().equals(key)) {
value = (int[]) mEntry.getValue();
}
}
return value;
}
Then I tried one of the answers and added
for(int i = 0; i < value.length; i++){
value[i] = Integer.valueOf(String.valueOf(value[i]), 16);
}
before the return. Now it works... but I dont know why it works :(
In any typed language int/number values have no format. The way Java stores int values is as 4 byte number using Two's complement, so 0 or 0x0 or 00 (octal) or 0b is the same value: 32 zeros in a binary word.
SECOND EDIT:
I think you are over-engineering. What you should use is a
Map<String,int[]> map;
then, if you write map.get(key), you'll obtain what you're looking for.
NEW EXPLANATION: The previous solution worked because when you read the XML stored the values as decimal ones:
String s="80";
int i= Integer.valueOf(s); //it stores 80 (decimal value)
int value= Integer.valueOf(String.valueOf(i),16); //It stores 128, or 0x80 (hex value)
for(int i = 0; i < value.length; i++){
value[i] = Integer.valueOf(String.valueOf(value[i]), 16);
}
Try this. If you want the hex value. Or in case if you want hex string you can use below code.
Integer.toHexString(integerValue)
Related
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!
Is there a better(Faster) way to split a binary string into an Array?
My code That loops and substring every 8 characters in one element.
binary = my binary string(Huge) : "1010101011111000001111100001110110101010101"
int index = 0;
while (index < binary.length()) {
int num = binaryToInteger(binary.substring(index, Math.min(index + 8,binary.length())));
l.add( num);
temp = temp+ String.valueOf(num);
index += 8;
}
What I am trying to do is to split my binary string into pieces of 8 characters 10101010 and then get the int value of the 8 characters and will store that in arraylist witch in this case was l
My code is working but is very time consuming.. Is there a faster way of getting this done?
It's easy using regex:
binary.split("(?<=\\G.{8})");
However, it creates an array of strings. I don't get your will of creating an array of integers, since binary strings don't fit into this type (they can start with "0" and they can be really long).
I think there are mutiple options using Regex, substring, split etc available in java or Google Guavas - Splitter.fixedLength().
Splitter.fixedLength(8).split("1010101011111000001111100001110110101010101");
This Split a string, at every nth position clearly explain the performance of various functions.
It would probably faster using toCharArray:
Long time = System.currentTimeMillis();
List<Integer> l = new ArrayList<>();
int index = 0;
String binary =
"1010101011111000001111100001110110101";
char[] binaryChars = binary.toCharArray();
while (index < binaryChars.length) {
int num = 0;
for (int offset = 0; offset < Math.min(8, binary.length() - index); offset++) {
int bo = index + offset;
if (binaryChars[bo] == '1') {
num += Math.pow(2, offset + 1);
}
}
l.add(num);
index += 8;
}
System.out.println(System.currentTimeMillis() - time);
Since you want to split into groups of eight bits, I guess, you want to decode bytes rather than ints. This is easier than you might think:
String binary = "1010101011111000001111100001110110101010101";
byte[] result=new BigInteger(binary, 2).toByteArray();
Maybe you can try making a for-each loop to go through each character in the string, combine them into 8-bit values and convert into bytes. I don't know if that will be faster, just a suggestion.
for (char c : binary.toCharArray() ) { do stuff }
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;
I need to convert a string to a corresponding int array in java. i wrote the following code but its not working as i expected .
String temp= "abc1";
int[] intArray = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
intArray[i] = Integer.parseInt(temp[i]);
}
I have written an rc4 encryption program which take the key and plain text as int arrays. So I need to convert the user specified key to int array before passing it to the encryption function. Is this the correct way of using key in encryption programs?
Use this to get the ASCII code
intArray[i] = (int)temp.charAt(i);
You can convert string to charArray. Travesing charArray you can convert as:
char[] c = inputString.toCharArray()
for(int i=0;i<c.length;i++)
int n = Integer.parseInt(c[i]);
if you are Using Java8 or higher then it might be helpful for you
String temp="abc1";
int[] intArray =temp.chars().map(x->x-'0').toArray();
System.out.println(Arrays.toString(intArray ));
int array would be [49, 50, 51, 1]
I solved this by using byte instead of int. Modified the rc4 to take byte array.
converted the string to byte using
String Nkey = jTextField2.getText();
jTextField3.setText(Nkey);
int i;
byte[] key = Nkey.getBytes();
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...