Convert a hex string to byte array

Hi,


I have this hex string, "1EA23", I would like to put this hex string into a byte array...
For example...

String hexString = "1EA23";
byte byteArray[] = new byte[4];

the value of byteArray should be...
byteArray[0] = (byte)0;
byteArray[1] = (byte)0x01;
byteArray[2] = (byte)0xEA;
byteArray[3] = (byte)0x23;

How can I do this??  I try to do it with substring...but it seems not work well...help please~~~~



Xenia
xenia27Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

x4uCommented:
You can do it like this:

int val = Integer.parseInt( hexString, 16 );
byteArray[0] = (byte) ( ( val >>> 24 ) & 0xff );
byteArray[1] = (byte) ( ( val >>> 16 ) & 0xff );
byteArray[2] = (byte) ( ( val >>> 8 ) & 0xff );
byteArray[3] = (byte) ( ( val >>> 0 ) & 0xff );

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
xenia27Author Commented:
OK...thanks~  This works exactly what I want!!  ^^
x4uCommented:
You are welcome. ;-)
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

CEHJCommented:
byte[] bytes = new BigInteger("1EA23", 16).toByteArray();
x4uCommented:
> byte[] bytes = new BigInteger("1EA23", 16).toByteArray();
This would an array that is only 3 in length.
x4uCommented:
I'm not really awake yet. ;-)
This would create an array that is only 3 bytes in length.
CEHJCommented:
OK - you've rumbled me - it can't be completely done in one line only ;-)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.