Android convert string to hex

How to convert String to Hex in Java

By mkyong | Last updated: February 28, 2020

Viewed: 218,036 (+960 pv/w)

Here are a few Java examples of converting between String or ASCII to and from Hexadecimal.

  • Apache Commons Codec – Hex
  • Integer
  • Bitwise

1. Apache Commons Codec

Both Hex.encodeHex and Hex.decodeHex can convert String to Hex and vice versa.

2. Integer

This example is easy to understand, use JDK Integer APIs like Integer.toHexString and Integer.parseInt(hex, 16) to convert the String to Hex and vice versa.

The idea is convert String Decimal Hex , for example char a , decimal is 97, hex is 61.

3. Bitwise

This bitwise conversion is similar to the Apache Commons Codec source code, read comment for self-explanatory.

Note
If you are confused, picks Apache Commons Codec for the safe bet.

References

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

But this creates a problem for a hex string with value between 80 to 9F.

I am doing byte dump of the ASCII and am seeing if it has the same hexa value. For values between 80 to 9F, doesnt happen so.

Article is updated, try Apache Commons Codec

Hi friend. How are you?
did you figure it out?
I am trying to solve this problem for days.

I will be very grateful for a return. hug

i have a solution for this problem. Except for a few decimals 129, 141, 143, 144, 157 im able to get the ascii values of them all. Let me know if u need the program.

Hello ,
I can not convert from hexadecimal to 255 caracters ascii table .
Sera you could help me .
An example is
80 == O , y = 79 .
is going to see a net 255 ascii character table .
I await response !!
Thank you .

i have a solution for this problem. Except for a few decimals 129, 141, 143, 144, 157 im able to get the ascii values of them all. Let me know if u need the program.

Читайте также:  Navionics boating 4pda android

Источник

android int to hex converting

I have to convert an int to an hex value. This is for example the int value:

To convert to a hex value i do:

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?

6 Answers 6

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.

Both Integer.toHexString, as well as String.format(«%x») do not support signs. To solve the problem, you can use a ternary expression:

Go through following code for Integer to hex and Hex to integer Conversion

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

where, 65536 is 2^16 now you can get the expected results . Happy coding 🙂

Not the answer you’re looking for? Browse other questions tagged android int hex or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Java converting int to hex and back again

I have the following code.

This equates to ffff8000

So, initially, it converts the value -32768 into a hex string ffff8000, but then it can’t convert the hex string back into an Integer.

In .Net it works as I’d expect, and returns -32768 .

I know that I could write my own little method to convert this myself, but I’m just wondering if I’m missing something, or if this is genuinely a bug?

10 Answers 10

That’s how you can do it.

The reason why it doesn’t work your way: Integer.parseInt takes a signed int, while toHexString produces an unsigned result. So if you insert something higher than 0x7FFFFFF , an error will be thrown automatically. If you parse it as long instead, it will still be signed. But when you cast it back to int, it will overflow to the correct value.

Читайте также:  Как посмотреть содержимое папки андроид

It overflows, because the number is negative.

Try this and it will work:

You may also want to use long instead of int (if the value does not fit the int bounds):

It’s worth mentioning that Java 8 has the methods Integer.parseUnsignedInt and Long.parseUnsignedLong that does what you wanted, specifically:

The name is a bit confusing, as it parses a signed integer from a hex string, but it does the work.

Try using BigInteger class, it works.

As Integer.toHexString(byte/integer) is not working when you are trying to convert signed bytes like UTF-16 decoded characters you have to use:

reverse you can use

Java’s parseInt method is actally a bunch of code eating «false» hex : if you want to translate -32768, you should convert the absolute value into hex, then prepend the string with ‘-‘.

There is a sample of Integer.java file :

The description is quite explicit :

Using Integer.toHexString(. ) is a good answer. But personally prefer to use String.format(. ) .

Try this sample as a test.

Below code would work:

Hehe, curious. I think this is an «intentianal bug», so to speak.

The underlying reason is how the Integer class is written. Basically, parseInt is «optimized» for positive numbers. When it parses the string, it builds the result cumulatively, but negated. Then it flips the sign of the end-result.

Источник

cvarta / Hex2StringMain.java

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

import java.io.UnsupportedEncodingException ;
import java.util.logging.Level ;
import java.util.logging.Logger ;
/**
*
* @author EtaYuy88
*/
public class Main <
private static final char [] HEX_CHARS = » 0123456789abcdef » . toCharArray ();
public static void main ( String [] args )
<
try
<
String helloWorldInHex = HexStringConverter . getHexStringConverterInstance() . stringToHex( » HELLO WORLD » );
System . out . println( » ‘HELLO WORLD’ in HEX : » + helloWorldInHex);
System . out . println( » Reconvert to String : » + HexStringConverter . getHexStringConverterInstance() . hexToString(helloWorldInHex));
>
catch ( UnsupportedEncodingException ex)
<
Logger . getLogger( Main . class . getName()) . log( Level . SEVERE , null , ex);
>
>
>

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Читайте также:  Все для смартфона андроида sony

Источник

Convert RGB to Hex using java code — Android [duplicate]

I’m converting RGB to Hexadecimal Colors using this code. I have 3 Edittext to input R, G and B. Now what I want to do is to convert it without using the API. Like converting and computing it with my own code and not by toHexString(). can someone help me to do that? Thanks a lot. Here is my code.

2 Answers 2

Assuming r , g and b values in the range [0, 255]:

Read java.util.Formatter javadoc for more formatting options.

So you want to do it without toHexString for some reason.

What you’re looking for is a way to convert a base 10 number to a base 16 number. You want to code it yourself, but not actually code it yourself obviously, since you’re here. Right?

Divide the number by 16. Convert the remainder to Hex if greater than 9 by;

Etcetera, you get the idea.

Then take your quotient from the first part and, if greater than 16, divide it by 16 again, take the remainder and convert it to hex again using the selfsame switch statement mentioned above.

Lather, rinse, and repeat, appending each new answer to the front of the string, until you’ve got the full value.

Example: 255/16 = 15r15 15 (converted to hex using the above switch) = «F»; And again.

Now one more example, with the number 146:

Converting to hex: 92.

Let me know if you actually want me to write out the code for you. But if you do, you may as well just use toHexString() since it’ll be more efficient than whatever I write for you, and since you wouldn’t be writing the code yourself either way.

Edit: some pseudo-ish code so you can figure out how to code it:

Then put the case statement like above into a function and call it on the two things in a row like

Which you’d call like makeHex(redMain);

And then you just have to append the strings in the right order, so it would look like;

And then put them all together with a hashtag like

But I would seriously just use toHexString since there are likely a bunch of things wrong with this way of doing it.

Источник

Оцените статью