String (MAC Address) to Byte Array

Hi,

I have this hex string, "111111111A12", (basicall it a MAC Address). I wanna convert it into a byte array.

Eg.
String hexString = "111111111A12";
byte byteArray[] = new byte[6];

the value of byteArray should be...
byteArray[0] = (byte)0x11;
byteArray[1] = (byte)0x11;
byteArray[2] = (byte)0x11;
byteArray[3] = (byte)0x11;
byteArray[4] = (byte)0x1A;
byteArray[5] = (byte)0x12;

I tried doing this using ...., but no success

int val = Integer.parseInt( hexString, 16 ); --> I thing i'm wrong here (i've tried diff. value, ain't know what i'm doing here, waste 2 days fro this :) )

byteArray[0] = (byte) ( ( val >>> 40 ) & 0xff );
byteArray[1] = (byte) ( ( val >>> 32 ) & 0xff );
byteArray[2] = (byte) ( ( val >>> 24 ) & 0xff );
byteArray[3] = (byte) ( ( val >>> 16 ) & 0xff );
byteArray[4] = (byte) ( ( val >>> 8 ) & 0xff );
byteArray[5] = (byte) ( ( val >>> 0 ) & 0xff );

But it does not help. Any suggestions....

Vicky
LVL 5
vks_vickyAsked:
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.

objectsCommented:
byteArray[0] = Byte.parseByte(hexString.substring(0, 2), 16);
byteArray[1] = Byte.parseByte(hexString.substring(2, 4), 16);
...
0
objectsCommented:
or do it in a loop

for (int i=0; i<byteArray.length; i++)
{
  byteArray[i] = Byte.parseByte(hexString.substring(i*2, (i+1)*2), 16);
}
0
CEHJCommented:
BigInteger bi = new BigInteger("111111111A12", 16);
byte[] bytes = bi.toByteArray();
0

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
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

vks_vickyAuthor Commented:
CHEJ ur code works fine, but on using different MAC Address like abcdef121001, i get -ve values, any idea of how to resolve these....
0
CEHJCommented:
Yes, byte in Java is a signed value, so you need to 'unsign' it:

int i = whateverNegativeByte & 0xFF;

You should do that for each element anyway actually
0
vks_vickyAuthor Commented:
objects using ur methor i get error ....

"java.lang.IllegalStateException
      org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:350)"
0
vks_vickyAuthor Commented:
CHEJ, it works like charm. Tnx.
0
CEHJCommented:
:-)
0
aozarovCommented:
vks_vicky,
you need to be aware that BigInteger supress leading zeros.
So new BigInteger("00000abbccdd", 16).toByteArray().length(); which is a valid MAC address will return you 4 bytes and not 6 as you might expect.
0
a_bCommented:
@aozarov:
Opening an old thread....but is there any work around to the leading zeroes issue?
0
CEHJCommented:
What makes you ask a_b?
0
a_bCommented:
BigInteger bi = new BigInteger("000111111A12", 16);
byte[] bytes = bi.toByteArray();

My mac address has leading zeros that disappear the when I use your code snippet.
0
objectsCommented:
thats right, you can't use that with leading zeroes (without manually correcting)
0
CEHJCommented:
It's not a problem - you know you're expecting a six-byte length
0
CEHJCommented:
String mac = String.format("%012X", bi.longValue());
0
objectsCommented:
> My mac address has leading zeros that disappear the when I use your code snippet.

thats why that technique is often avoided in the real world, all the stuffing around required to make it work for all cases defeats the purpose so usually simpler to just loop.

0
a_bCommented:
@CEJH: String.format("%012X", bi.longValue()); does not solve my problem as I need to have bytes have the correct info. Any ideas on how to do that?
0
CEHJCommented:
>>as I need to have bytes have the correct info.

I'm not sure what you mean by that unfortunately. What exactly is the problem?
0
objectsCommented:
rotfl, someones head is stuck in the sand ;)
0
a_bCommented:
@CEJH: What I meant was when I execute BigInteger bi = new BigInteger(macStr,16); the leading zeroes are already gone by the time I come to my next set of operations which is converting to bytes. So now, the bytes are not aware of the fact that there were leading zeros.
0
CEHJCommented:
You're making what's known as a 'category error'. Numbers have no concept of 'leading zeros' - only strings do. What you need to do is format the number as a string, which is what my code does
0
CEHJCommented:
If otoh you're working with arrays, you could do something like:
byte[] destination = new byte[6];
int ix = destination.length - source.length;
for (byte b : source) {
	destination[ix++] = b;
}

Open in new window

0
a_bCommented:
Thanks.....I think I need a coffee break.....my head is really stuck in the gutter..........feeling kinda stupid right now........
0
objectsCommented:
Which is exactly one of the reason *not* for using it. If you're going to loop anyway just calculate the values in the loop. Not to mentioned creating a second byte array for a simple conversion.
0
objectsCommented:
convert to a byte array
create a second byte array
copy first byte array into new byte array

or

create byte array
loop to populate array

simple choice :)
0
CEHJCommented:
a_b, it would help if i knew exactly what you need to do. I don't know whether you need it as a String or what or even what you're starting with
0
a_bCommented:
I resolved the issue. I was starting with  a String mac address, converting to byte  to do some binary operations on them.
0
CEHJCommented:
Good :-)
0
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.