rosesr
rosesr

Reputation: 789

How to convert a String Mac Address to a Byte array

I have got the String MacAddress, which i need to convert in to a byte array. Java wouldn't let me do a direct conversion throwing a numberformat exception. This is what I'm doing right now

clientMac[0] = (byte)Integer.parseInt(strCameraMacId.substring(0, 2));

I tried doing it step by step

String mc = strCameraMacId.substring(0,2);
        int test = Integer.parseInt(mc);
        clientMac[0] = (byte) test;

But the String mc consists of a value "08" and after doing the int to byte converion im losing the zero. the mac address im trying to convert is "08-00-23-91-06-48" and I might end up losing all the zeros. will I? and has anyone got an idea regarding how to approach this issue?

Thanks a lot

Upvotes: 3

Views: 6172

Answers (3)

Sean F
Sean F

Reputation: 4605

The IPAddress Java library will do this for you and will handle lots of different MAC address string formats, like aa:bb:cc:dd:ee:ff, aa-bb-cc-dd-ee-ff, aabb.ccdd.eeff, and so on. Disclosure: I am the project manager for that library.

Here is how to get a byte array:

    String str = "aa:bb:cc:dd:ee:ff";
    MACAddressString addrString = new MACAddressString(str);
    try {
         MACAddress addr = addrString.toAddress();
         byte bytes[] = addr.getBytes();//get the byte array
         //now convert to positive integers for printing
         List<Integer> forPrinting = IntStream.range(0, bytes.length).map(index -> 0xff & bytes[index]).boxed().collect(Collectors.toList());
         System.out.println("bytes for " + addr + " are " + forPrinting);
    } catch(AddressStringException e) {
        //e.getMessage provides validation issue
    }

The output is:

    bytes for aa:bb:cc:dd:ee:ff are [170, 187, 204, 221, 238, 255]

Upvotes: 1

ArjunShankar
ArjunShankar

Reputation: 23680

You are not losing the '0'. Because a byte is not a string, and 8 and 08 are the same.

But more important is this mistake in your code:

You're using the parseInt method. This parses your addresses as decimal integers. This won't work, because MAC addresses, when split the way you show them are usually HEX digits. You can come across 'A8' instead of '08' for example.

You need to use a different method:

Integer.parseInt(String s, int radix)

Pass the radix as 16 and you should be good.

Upvotes: 5

MrWuf
MrWuf

Reputation: 1498

The zero is going to be implied in the byte value. Remember that 0x08 == 8. You should be able to convert your to an array of 6 bytes. Youre approach is fine, just remember that if you are going to convert this back to a string, that you need to let Java know that you want to pad each number back to 2 chars. That will put your implied zeros back in place.

Upvotes: 4

Related Questions