Converting String Mac Address to Hex

泄露秘密 提交于 2020-01-06 07:56:14

问题


I am trying to convert a string macaddress to hex value. I got a C# code which does the same thing but when I use the java code it gives me negative values. as in the C# code returns signed integer but how do i do the same in Java

following is part of my code

Integer hex = Integer.parseInt(MacAddress.subString(0,2), 16 );
MacAddress[0] = hex.byteValue();

i get something like 148 on the c# code and java returns -148 how can I sort this out thanks

UPDATE

and I just realised that my c# code returns a value of 214 to "D6" a part of the macaddress and the java code returns -42 which is strange


回答1:


String MacAddress="D6";
Integer hex = Integer.parseInt(MacAddress.substring(0,2), 16 );
byte byteArray=(byte) hex.intValue();
System.out.println(hex+"|"+hex.byteValue()+"|"+byteArray[0]+"|"+(int)(byteArray[0]&(0xff)));        

byteValue() will give you your byte in signed format.You can store this in your byte array without any worries,just take care of conversion into unsigned value before using it.

also see unsigned byte from signed byte

If you dont want this conversion from signed to unsigned Make your MacAddress as char[]. char are by default considered as unsigned.




回答2:


Since bytes are signed in Java, you should probably do hex.intValue() instead (or just rely on the auto-unboxing).




回答3:


You can just access the "hex" variable directly

System.out.println(hex);

This is because Java automatically unboxes the Integer object to the primitive int. This is helpful in many cases particularly to do with datastructures.




回答4:


This is a representation issue. The "correct" data is stored in the computer internally. The default behavior is for Java to display a byte represented as a signed decimal in the range -128 to 127. Since you are using the binary data stored in the computer, you should print out the hex or binary representation of that value. This will help avoid the confusion caused here.




回答5:


ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress());

    NetworkInterface network = NetworkInterface.getByInetAddress(ip);

    byte[] mac = network.getHardwareAddress();

StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));        
        }
        System.out.println(sb.toString());

Copy from here : http://www.mkyong.com/java/how-to-get-mac-address-in-java/comment-page-1/#comment-139182



来源:https://stackoverflow.com/questions/12527926/converting-string-mac-address-to-hex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!