将字符串Mac地址转换为十六进制 [英] Converting String Mac Address to Hex

查看:2642
本文介绍了将字符串Mac地址转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将字符串macaddress转换为十六进制值。我得到了一个C#代码,它可以做同样的事情,但是当我使用java代码时,它给了我负值。在C#代码中返回带符号整数,但我如何在Java中执行相同的操作



以下是我的代码的一部分

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

我在C#代码上得到类似于148的东西,而java返回-148,我怎样才能解决这个问题



更新



我刚刚意识到我的c#代码返回值为214到D6的macaddress和java代码返回-42这是奇怪的

解决方案

  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()会为您提供签名格式的字节。您可以将其存储在您的字节数组中任何担心,只需在使用前将其转换为无符号值即可。

另请参阅带符号字节的无符号字节



如果你不希望这种转换从signed到unsigned使你的MacAddress as char []。
char默认为无符号。


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

解决方案

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.

这篇关于将字符串Mac地址转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆