天天看點

android NFC TAGID的進制轉換

去年做了個app用到了NFC,當時擷取到的id需要進制轉換後才能與硬體廠商那邊對接,是以搞了幾個進制轉換的方法

先上進制轉的代碼:

/**
     * 轉十六進制
     * @param bytes
     * @return
     */
    private String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    /**
     * 轉反向十六進制
     * @param bytes
     * @return
     */
    private String toReversedHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i) {
            if (i > 0) {
                sb.append(" ");
            }
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
        }
        return sb.toString();
    }

    /**
     * 轉十進制
     * @param bytes
     * @return
     */
    private long toDec(byte[] bytes) {
        Log.e(Constants.TAG,"數組長度"+bytes.length);
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
            Log.e(Constants.TAG,"value="+value+",result="+result+",factor="+factor);
        }
        return result;
    }

    /**
     * 轉反向十進制
     * @param bytes
     * @return
     */
    private long toReversedDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = bytes.length - 1; i >= 0; --i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }
           

然後擷取NFC的TAGID,并轉換進制

        // 取出封裝在intent中的TAG
        tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);//也可使用intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)直接擷取TAGID;
        tagbytes = tagFromIntent.getId();
        String NFC_ID = String.format("%010d", toDec(tagbytes));//不足十位數,左補0, 0代表前面要補的字元 10代表字元串長度,d表示參數為整數類型(不足補位看你自己的需求!)