Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,495,102字

该文章投稿至Nemo社区   Java  板块 复制链接


MAC地址转LONG

发布于 2016/08/19 11:32 1,684浏览 0回复 1,556

/**
 * Created by nemo on 16-8-19.
 */
public class MacUtils {

    /**
     *
     * @param arg
     */
    public static void main(String arg[]){
        String mac = "60:02:B4:FE:50:55";
        byte mbyte[] = getMacBytes(mac); //mac地址转字节,码
        long res = bytesToLong(mbyte); //字节码数组转Long
        System.out.println("mac:"+mac+"\nLong:"+res);
    }

    /**
     * 根据mac地址取得字节码数组
     * @param mac
     * @return
     */
    public static byte [] getMacBytes(String mac){
        byte []macBytes = new byte[8];
        String [] tempStr = mac.split(":");

        for(int i = 0;i < tempStr.length; i++){
            int value = Integer.parseInt(tempStr[i],16);
            macBytes[i] = (byte) value;
            System.out.println(value);
        }
        return macBytes;
    }

    /**
     * 字节数组转Long
     * @param b
     * @return
     */
    public static long bytesToLong(byte[] b) {
        long s = 0;
        long s0 = b[0] & 0xff;// 最低位
        long s1 = b[1] & 0xff;
        long s2 = b[2] & 0xff;
        long s3 = b[3] & 0xff;
        long s4 = b[4] & 0xff;// 最低位
        long s5 = b[5] & 0xff;
        long s6 = b[6] & 0xff;
        long s7 = b[7] & 0xff;

        // s0不变
        s1 <<= 8;
        s2 <<= 16;
        s3 <<= 24;
        s4 <<= 8 * 4;
        s5 <<= 8 * 5;
        s6 <<= 8 * 6;
        s7 <<= 8 * 7;
        s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;
        return s;
    }

}



点赞(0)

上一个文章:树莓派自动连接

下一个文章:DateUtils

点了个评