Convert java function which uses bytes to Kotlin

2019-07-19 09:10发布

问题:

I have a problem with converting function written in java to Kotlin specific.

Here is written in Java:

 private boolean isOldOemCommissioningFormat(byte[] assetData) {
    if (assetData == null
            || assetData.length < mAssetDataDelimeterByteCount + mAssetDataOwnerIdByteCount + mAssetDataIdLeadingZerosByteCount + mAssetDataIdByteCount)
        return false;

    int oemMarkerIndex = mAssetDataDelimeterByteCount + mAssetDataIdLeadingZerosByteCount + mAssetDataIdByteCount;
    if (assetData[oemMarkerIndex] ==  PARTIAL_OEM_MARKER || assetData[oemMarkerIndex] == FULL_OEM_MARKER)
        return ((assetData[oemMarkerIndex + 1] >> 6) & 0x01) == 0;

    return false;

}

However, when i am converting to Kotlin using Android Studio IDE converter it gives me this:

 private fun isOldOemCommissioningFormat(assetData: ByteArray?): Boolean {
    if (assetData == null || assetData.size < mAssetDataDelimeterByteCount + mAssetDataOwnerIdByteCount + mAssetDataIdLeadingZerosByteCount + mAssetDataIdByteCount)
        return false

    val oemMarkerIndex = mAssetDataDelimeterByteCount + mAssetDataIdLeadingZerosByteCount + mAssetDataIdByteCount
    return if (assetData[oemMarkerIndex] == PARTIAL_OEM_MARKER || assetData[oemMarkerIndex] == FULL_OEM_MARKER) assetData[oemMarkerIndex + 1] shr 6 and 0x01 == 0 else false

}

It gives wrong convertion i guess, plus the 'shr' is marked on red as unresolved reference.

How can I convert it properly?

The other variables are:

   public static final byte PARTIAL_OEM_MARKER = '#';
public static final byte FULL_OEM_MARKER = '&';
public static final int OEM_COMMISSIONING_CUSTOMER_ID_ENCODING_CHARACTERS_COUNT = 40;
public static final int OEM_COMMISSIONING_CUSTOMER_ID_ENCODING_FIRST_CHARACTER_INDEX = 64;

and

 private final int mAssetDataIdLeadingZerosByteCount;
private final int mAssetDataIdByteCount;
private final int mAssetDataDelimeterByteCount;
private final int mAssetDataOwnerIdByteCount;

回答1:

In Kotlin "shr" available only for Int and Long, try to convert your value

assetData[oemMarkerIndex + 1].toInt()


回答2:

Convert byte from assetData[oemMarkerIndex + 1] to Int: assetData[oemMarkerIndex + 1].toInt()