I need to know how to add strings in the form of an integer so for example if I need to use setBackgroudColor(int) it can be like so :
String a = "15"; // Here I mean like its user changeable , so the user can change only this part of the int;
View.setBackgroundColor("0x" + a + "000000");
To clarify more , I want these two digits to be user changeable , and still here is an example :
1 + 1 = 2 // which is I don't want
1 + 1 = 11 // which I want
Please help me in this case , if you need anything more please tell me ...
You can do this directly in binary math. To set ARGB, you could use the following logic:
int a = 0x10;
int r = 0x20;
int g = 0x30;
int b = 0x40;
int finalColor = (a << 24) + (r << 16) + (g << 8) + b;
Typing 0x (that's the number zero and the letter "X") means the number is in hexadecimal format. This means you could say this:
int red = 0xff; // This is valid.
The logic I gave you allows you to specify colours in hex, and get the int value of your color.
The operation "<<" is a "binary shift", and it shifts your bits into the correct location.
For example:
int x = 1;
x = x << 1;
// Now x is equal to 2 (since 1 shifted to the left is 10, which is 2 in binary).
The code I gave you above shifts all the colours properly.
Try out that logic in your code :)
I'm available if you have any more questions.
While the above answers should do the trick, for your case you might look into the Color.argb() method. Not sure how you're getting user input, but let's just assume they're EditText objects:
EditText a, r, g, b;
//initialize them
int aInt, rInt, gInt, bInt;
try {
aInt = Integer.valueOf(a.getText().toString());
bInt = Integer.valueOf(b.getText().toString());
cInt = Integer.valueOf(c.getText().toString());
dInt = Integer.valueOf(d.getText().toString());
} catch (NumberFormatException ex) {
//Throw a warning dialog that the user's input was invalid
}
view.setBackgroundColor(Color.argb(aInt, rInt, gInt, bInt));
This is of course assuming you're getting input in the form of integers 0-255.
EDIT: Actually, if you're just wanting to change the alpha part of it, it's much easier. You could just get the input from the user as an integer from 0-255, validate it, and do this:
EditText alpha;
String alphaString;
try {
alphaString = Integer.toHexString(alpha.getText().toString());
} catch (NumberFormatException ex) {
//Throw warning
}
view.setBackgroundColor(Color.parseColor("#" + alphaString + "000000"));
Related
I am converting 4 integers into binary and everything works fine until it has to convert a zero.
for example:
int subnet1 = 255;
int subnet2 = 255;
int subnet3 = 255;
int subnet4 = 0;
binarystring = Integer.toBinaryString(subnet1)
+ Integer.toBinaryString(subnet2)
+ Integer.toBinaryString(subnet3)
+ Integer.toBinaryString(subnet4);
BinaryView.setText(binarystring);
text would look like this: 11111111 11111111 11111111 0 (without the space inbetween)
why wont it convert the 0 to 00000000 ??
Because value for "0000000" is same for "0" that's why it set as "0".
If you want to print that result. Just make a string of "0000000" for printing. Because int value always convert it.
Why? By design. From the documentation:
This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.
(Emphasis added.)
If you want 8 characters, append the result to a string of 7 zeros, and take the last 8 characters. In pseudo code:
intermediateString = "0000000" + Integer.toBinaryString( 0 ); // obviously don't hard code zero; just for example
finalString = intermediateString.substring( intermediateString.length() - 8);
If you read the documentation here: https://developer.android.com/reference/java/lang/Integer.html#toBinaryString(int)
It tells you:
The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.
As for the RGB value maximum value for each can be 255(length is 3) but for each color. For eg : if Color.red(c) gives the value 12(length is 2) for red then i want to add 0 in front and make it 012 how can i do that. It was possible if i could check the length but i do not know how to do it.
To check the length you can try something like
int red = Color.red(c);
if (red < 10) {
//0...9
} else if (red < 100) {
//10..99
} else {
//100..255
}
In the each if you can add to the value as many zeros as you want.
String colorLeadingZeroes = String.format("%03d", Color.red(c));
this will force the result to be a string of three digits with leading zeros replacing the spaces
I am getting response from server in string format like
V1YYZZ0x0000010x0D0x00112050x0C152031962061900x0D410240x0E152031962061900x0F410240x1021TATADOCOMOINTERNET101
Then I am converting it in to byte array because i need to get value from this byte by byte.
I tried to use
Arrays.copyOfRange(original,
from , to);
but it work on index basis not on byte basis.
I also tried following solution but it also truncating String(if I use string instead of byte[]) on length basis.
public static String truncateWhenUTF8(String s, int maxBytes) {
int b = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
// ranges from http://en.wikipedia.org/wiki/UTF-8
int skip = 0;
int more;
if (c <= 0x007f) {
more = 1;
} else if (c <= 0x07FF) {
more = 2;
} else if (c <= 0xd7ff) {
more = 3;
} else if (c <= 0xDFFF) {
// surrogate area, consume next char as well
more = 4;
skip = 1;
} else {
more = 3;
}
if (b + more > maxBytes) {
return s.substring(0, i);
}
b += more;
i += skip;
}
return s;
}
I know how to calculate string in byte length but it giving only full string length in byte like
Here is how I need to extract packet on byte basis.
Above codes and parameters is only example. I need to get byte by byte from string/byte array.
I searched lot but didn't get any solution or link which I can refer. I am not getting how to split string using byte length because I know byte length for each parameter and for value also.
Please give me any reference or hint.
To determine what is equal to one byte in a String is not trivial. Your String contains bytes in hexadecimal text form: 0x0D (one byte, equal to 13), but also contains values as substrings. For example 1024 can be interpreted as an integer which in this case fits into 2 bytes, but could also be interpreted as a text made up by 4 chars, totaling to 8 bytes.
Anyways, I would split the string using a regular expression, and then further split the parts to length and value:
String message = "V1YYZZ0x0000010x0D0x00112050x0C152031962061900x0D41024"+
"0x0E152031962061900x0F410240x1021TATADOCOMOINTERNET101";
String regex = "(0)(x)(\\w\\w)";
String[] parts = message.split(regex);
Log.d(TAG,"HEADER = "+parts[0]);
for (int i=1; i<parts.length; i++) {
String s = parts[i];
// Only process if it has length > 0
if (s.length()>0) {
String len = "", val = "";
// String s is now in format LVVVV where L is the length, V is the value
if (s.length() < 11) {
// 1 character indicates length, up to 9 contains value
len = s.substring(0, 1);
val = s.substring(1);
} else if (s.length() > 10) {
// 2 characters indicate length, up to 99 contains value
len = s.substring(0, 2);
val = s.substring(2);
} else if (s.length() > 101) {
// 3 characters indicate length, up to 999 contains value
len = s.substring(0, 3);
val = s.substring(3);
}
Log.d(TAG, "Length: " + len + " Value: " + val);
}
}
This produces the following output:
D/Activity: HEADER = V1YYZZ
D/Activity: Length: 0 Value: 001
D/Activity: Length: 1 Value: 1205
D/Activity: Length: 15 Value: 203196206190
D/Activity: Length: 4 Value: 1024
D/Activity: Length: 15 Value: 203196206190
D/Activity: Length: 4 Value: 1024
D/Activity: Length: 21 Value: TATADOCOMOINTERNET101
Then you can check the packages (the first two package in the header is not needed), convert Strings to whatever you would like (e.g. Integer.parseInt(val))
If you explain the structure of the header (V1YYZZ0x0000010x0D0x0011205), I can improve my answer to find the message count.
I think it is doable with Scanner
import java.util.Scanner;
public class Library {
public static void main(String[] args) {
String s = "V1YYZZ0x0000010x0D0x001120"
+ "50x0C152031962061900x0D410240x0E152031962061900x0F410240x1"
+ "021TATADOCOMOINTERNET101";
// Skip first 9? bytes. I'm not sure how you define them
// so I just assumed it is 26 chars long.
s = s.substring(26, s.length());
System.out.println(s);
Scanner scanner = new Scanner(s);
// Use byte as delimiter i.e. 0xDC, 0x00
// Maybe you should use smth like 0x[\\da-fA-F]{2}
// And if you want to know that byte, you should use
// just 0x and get first 2 chars later
scanner.useDelimiter("0x\\w{2}");
// Easily extracted
int numberOfParams = scanner.nextInt();
for (int i = 0; i < numberOfParams; i++) {
String extracted = scanner.next();
// Length of message
int l = extracted.length();
boolean c = getLength(l) == getLength(l - getLength(l));
l -= getLength(l);
l = c ? l : l-1;
System.out.println("length="
+ extracted.substring(0, extracted.length()-l));
System.out.println("message="
+ extracted.substring(extracted.length()-l, extracted.length()));
}
// close the scanner
scanner.close();
}
// Counting digits assuming number is decimal
private static int getLength(int l) {
int length = (int) (Math.log10(l) + 1);
System.out.println("counted length = " + length);
return length;
}
}
We definitely need more information about rules, how string is formed. And what exactly you need to do. This code might be good enough you. And without comments it is really short and simple.
This is not a answer to accessing a byte array byte by byte, but is an answer for the situation in which you find yourself.
Your explanation and description have the appearance of being confused as to what it is that you are really getting from the server (e.g. it is quite hard to represent "V1YYZZ0x0000010x0D0x001120" as a 9 byte field (note it probably ends on the 2, not the 0)). Alternately, that you are using the wrong method to get it from the server, or not getting it as the intended data type.
Your code indicates that you believe that what you are getting is a UTF8 string. The data shown in your question does not appear to indicate that it is intended to be in that format.
Keep in mind when doing something like this that some other programmer had to create structure for the data that you are seeing. They had to define it somewhere with the intent that it be able to be decoded by their intended recipients. Unless there are other considerations (security, minimal bandwidth, etc.), such formats are usually defined in a way that is both easy to encode and decode.
The existence of the multiple "0x"-ASCII-encoded hexadecimal numbers --particularly the single byte representing the parameter (called "varam" in your graphic)-- strongly implies that this data was intended to be interpreted as a ASCII encoded string. While that might not be the case, it should be kept in mind when looking at the problem from a larger perspective.
You are having to put too much effort into decoding the information you are getting from the server. It, probably, should be relatively easy unless there are considerations why it would have intentionally been made difficult.
All of this indicates that the real problem exists in an area for which you have provided us with no information.
Step back:
Think about things like:
How are you receiving this from the server (what function/interface)?
In the call requesting the information from the server is there a way to specify the encoding type be bytes, an ASCII string, or some other format that is easier to deal with than UTF8? At a minimum, it appears to be clear that the data was not intended to be handled as a UTF8 string. There should be a way for you to get it without it having been converted to UTF8.
Also, you should try to find an actual specification for the format of the data. You have not explained much about the source, so it may be you are reverse-engineering something and have no access to specifications.
Basically, it looks like this is a problem where it might be a good idea to step back and ask if you are starting from the point that makes it easiest to solve and if you are headed in the right direction for doing so.
I'm sure I'm missing something obvious...
String.getBytes();
And if you want to process it in order taking defined objects from the array, just wrap using
ByteBuffer.wrap();
The result being something along the lines of:
String s = "OUTPUT FROM SERVER";
byte[] bytes = s.getBytes();
ByteBuffer bb = ByteBuffer.wrap(bytes);
What did I miss from the initial question? :/
I have to convert an int to an hex value. This is for example the int value:
int_value = -13516;
To convert to a hex value i do:
hex_value = Integer.toHexString(int_value);
The value that I should get is : -34CC (I don't know if i should make it positive).
The thing is that doing the conversion that way, the value that I get is: ffff cb34
Can't I use this function to make this conversion?
Documentation says Integer.toHexString returns the hexadecimal representation of the int as an unsigned value.
I believe Integer.toString(value, 16) will accomplish what you want.
public static int convert(int n) {
return Integer.valueOf(String.valueOf(n), 16);
}
// in onstart:
Log.v("TAG", convert(20) + ""); // 32
Log.v("TAG", convert(54) + ""); // 84
From: Java Convert integer to hex integer
Both Integer.toHexString, as well as String.format("%x") do not support signs. To solve the problem, you can use a ternary expression:
int int_value = -13516;
String hex_value = int_value < 0
? "-" + Integer.toHexString(-int_value)
: Integer.toHexString(int_value);
String.format("#%06X", (0xFFFFFF & colorYellow));
Output: #FFC107
Go through following code for Integer to hex and Hex to integer Conversion
public class MainActivity extends Activity {
int number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number = 678668;
Log.i("ACT", "Integer Number " + number);
/**
* Code for convert integer number to hex number. two mwthods.
*/
Log.i("ACT", String.format("#%x", number)); // use lower case x for
// lowercase hex
Log.i("ACT", "#" + Integer.toHexString(number));
/**
* Code for convert hex number to integer number
*/
String hex = Integer.toHexString(number).replace("/^#/", "");
int intValue = Integer.parseInt(hex, 16);
Log.i("ACT", "Integer Number " + intValue);
}
}
I don't think the above answers would give you the exact value for the signed bits. For example the value of 11 is 0B but the value of -11 would be F5 and not -B since 2's complement gets into the game to solve this i have modified the above answer
int int_value = -11;
String hex_value = int_value < 0
? Integer.toHexString(int_value+65536) : Integer.toHexString(int_value);
String shortHexString = hex_value.substring(2);
where, 65536 is 2^16 now you can get the expected results . Happy coding :)
List item
For my app I have created a QR Code, then took that bitmap and added text to the bitmap, however I need the text not to extend longer then the bitmap is. So what I want to do is create an Array of the text by taking 25 characters then find the last index of (" ") in that 25 character section. at that space I want to be able to replace that space that was located with \n to start a new line.
So the plan is if I have a String that looks like "Hello this is my name and I am longer than 25 charters and I have lots of spaces so that this example will work well."
I want it to out up this
Hello this is my name and
I am longer than 25
charters and I have lots
of spaces so that this
example will work well.
To make this I counted 25 characters then went back to the most resent space, at that point I hit enter, I want my app to do this for me.
I am not very good at English so if something doesn't make sense tell me and I will try to explain it. Thanks
I haven't tested this but you can try it and tweak as necessary
String fullText = "your text here";
String withBreaks = "";
while( fullText.length() > 25 ){
String line = fullText.substring(0,24);
int breakPoint = line.lastIndexOf( " ");
withBreaks += fullText.substring(0,breakPoint ) + "\n";
fullText = fullText.substring( breakPoint );
withBreaks += fullText;
char [] way (more C like):
public static String reduceLength(String s, int len){
char [] c = s.toCharArray();
int i=len, j=0, k;
while(true){
for(k=j; k<=i; k++){
if (k >= s.length()) return new String(c);
if (c[k] == ' ') j=k;
}
c[j] = '\n';
i= j+ len;
}
}
This isn't safe, just something i threw together.