android int to hex converting - android

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

Related

Need to round off two points after decimal digit

I'm working on an app and facing an issue. I've tried a number of solutions but nothing solved my problem.
I need to round off two digits after decimal point.
For Example.
9.225 should be rounded off to 9.23
Thank you.
For Kotlin use "%.2f".format(number), for Java use String.format("%.2f", number)
Result:
You can use String.format("%.2f", d), this will rounded automatically. d is your value.
OR
You can use this
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
Log.d(df.format(d));
You can get as a float value as well like below.
float value = Float.valueOf(df.format(d)); // Output will be 1.24
I would have gone with a probable over the top solution however this is what i came up with.
It uses regex to split the string value of the number passed and then rounds up/down depending on the leading digit after the decimal place. It will return a Double in the instance but you can change that if you like. It does throw IllegalArgumentException, but thats taste dependant.
/**
* #param value the value that is being transformed
* #param decimalPlace the decimal place you want to return to
* #return transformed value to the decimal place
* #throws IllegalArgumentException
*/
Double roundNumber(#NonNull Double value, #NonNull Integer decimalPlace) throws IllegalArgumentException {
String valueString = value.toString();
if(valueString.length()> decimalPlace+1){
throw new IllegalArgumentException(String.format("The string value of %s is not long enough to have %dplaces", valueString, decimalPlace));
}
Pattern pattern = Pattern.compile("(\\d)('.')(\\d)");
Matcher matcher = pattern.matcher(valueString);
if (matcher.groupCount() != 4) { //0 = entire pattern, so 4 should be the total ?
throw new IllegalArgumentException(String.format("The string value of %s does not contain three groups.", valueString));
}
String decimal = matcher.group(3);
int place = decimal.charAt(decimalPlace);
int afterDecimalPlace = decimal.charAt(decimalPlace + 1);
String newDecimal = decimal.substring(0, decimalPlace - 1);
newDecimal += afterDecimalPlace > 5 ? (place + 1) : place;
return Double.parseDouble(matcher.group(1) + "." + newDecimal);
}

Check if condition from json

I have an int value lets say 10, now i want to check whether 10 is less than 50 or not so i will write if condition as :
if(10<50){
}
But the problem here is that "<50" is coming from json in string format. So how to evaluate this condition?
If you are sure that JSON response will be in following format -
*characterNUMBER*
then you can get int value as follows -
String test = "<50";
int value1 = Integer.parseInt(test.replace("<", ""));
/*
* Using substring method
* String.subString(beginIndex, endIndex);
* Note: beginIndex is inclusive but endIndex is the exclusive
* */
int value2 = Integer.parseInt(test.substring(1,test.length()));
value1 and value2 both will extract int from that String.
For ease of use do create a method inside your Json POJO to return integer values-
public class JSONResponce{
.....
#SerializedName("some_string_value")
private String stringValue;
public int getIntValue(){
//do conversion of String to actual int here
return Integer.parseInt(stringValue.substring(1,stringValue.length()));
}
....
}
Happy coding !

convert String to int return NumberFormatException

i from API I receive next string:
String userId = "4463570100035744";
I need to convert it to int, so I tried next code:
try {
int id = Integer.parseInt(userId);
} catch (NumberFormatException e){
e.printStackTrace();
}
but I still catch exeption....
what can be the reason?
REASON: value is outside the range of an int
ACTION: You must use Long and not Integer .Use a long/Long instead.
Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648
Long.MAX_VALUE = 9223372036854775807
Long.MIN_VALUE = -9223372036854775808
4463570100035744 is too large a number for an Int32 variable. You could consider using a long variable type.
you take variable userId as String and you put integer value in it and then you parse it to convert in integer. Your mistake is you put integer value in String variable userId.
You need to put it like this :
String userId = "4463570100035744";
One more thing keep the size of variable in mind. I think value is too large then the size of int.
And now you edited your question, after people post answers to your actual problem.
You can refer to the docs for the Java primitive types to select the appropriate type for your variable: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
The primitive types available to store a number like your userId are:
byte (1 byte) Range: −128 to 127
short (2 bytes) Range: −32768 to 32767
int (4 bytes) Range: −2,147,483,648 to 2,147,483,647
float (4 bytes) Range: 3.4e−038 to 3.4e+038
long (8 bytes) Range: 9,223,372,036,854,775,808 to 9,223,372,036,854,755,807
double (8 bytes) Range: 1.7e−308 to 1.7e+038
Notice how your int is 4463570100035744 which compared to int has a difference of 4,463,567,952,552,097.
Your id variable would be best suited for a long.
try
{
long id = Long.parseLong(userId);
System.out.println("long id = " + id);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}

Android Bluetooth and sending an unsigned Hex value

I am currently working on a Android application that takes values from a text box and then sends it over bluetooth, all operations are in Hex values.
I have a convertion method that can take the string make give me the unsigned integer for the string, but once i place it in the byte array it becomes signed and the board that receives this cannot do signed hex.
This is how the process works:
//sample string to send
String toSend = "0BDD";
//sending the byte[] to the board over bluetooth
btOutputStream.write(SendByteData(toSend));
// --- perform the conversion to byte[] ---
public static byte[] SendByteData(String hexString)
{
byte[] sendingThisByteArray = new byte[hexString.length()/2];
int count = 0;
for( int i = 0; i < hexString.length() - 1; i += 2 )
{
//grab the hex in pairs
String output = hexString.substring(i, (i + 2));
//convert the 2 characters in the 'output' string to the hex number
int decimal = (int)(Integer.parseInt(output, 16)) ;
//place into array for sending
sendingThisByteArray[count] = (byte)(decimal);
Log.d(TAG, "in byte array = " + sendingThisByteArray[count]);
count ++;
}
return sendingThisByteArray;
}
The issue is as follows:
When the for for loop runs through the string and picks up "0B" it correctly gives me integer 11; then when the loop runs through "DD" it give me integer 221 which is also correct
When I perform the operation of
sendingThisByteArray[count] = (byte)(decimal);
11 gets correctly placed in sendingThisByteArray[0]
but for sendingThisByteArray[1] the number 221 gets changed to -35
I know that Java has signed bytes.. is there a way to put/place/change the byte array so i can place and number 221 or any other value higher than 127?
your help is greatly appreciated
You can convert from a signed integer to unsigned byte like this, by binary AND'ing it with 0xFF:
sendingThisByteArray[count] = (byte)(decimal & 0xFF);
This way you can send values from 0 to 255
I found the problem, when i tried to do unsigned hex into a byte array it would always put a sign, i had to create single byte to retain the unsigned hex
int zeroA = (int)(Integer.parseInt("0D", 16));
sendStream.write(unsignedToBytes((byte) zeroA));

Add string to int / Add ints in form of String

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"));

Categories

Resources