-1

I am trying to transpose my JAVA code to Kotlin. Can you please transpose this

String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"

This is the whole method. It is for reading NFC

     private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {
            // Get the Text
            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

        tvNFCContent.setText("NFC Content: " + text);
    }

Thank you.

Ibanez1408
  • 4,550
  • 10
  • 59
  • 110
  • Don't know which part is problematic, but perhaps this is a good starting point: https://stackoverflow.com/questions/48474520/how-do-i-use-javas-bitwise-operators-in-kotlin – Tarmo May 07 '20 at 10:03
  • `0063` is 51 decimal. Is that really the number you're supposed to use for this bitmask? – khelwood May 07 '20 at 10:06
  • That's what it is in the example. It doesn't have an explanation on what it is. – Ibanez1408 May 07 '20 at 10:13

2 Answers2

1

Probably you could try this:

val textEncoding = if (payload[0] and 128.toByte() == 0.toByte()) "UTF-8" else "UTF-16"
val languageCodeLength = (payload[0] and 52.toByte()).toInt()

Disclaimer: Not tested, but hopefully correct.

Animesh Sahu
  • 7,445
  • 2
  • 21
  • 49
0

If you are using IntelliJ IDEA, you can just copy the Java code and paste it into a Kotlin source file. The IDE should ask you, if you want the code to be converted to Kotlin.

For your two lines, the result is

var textEncoding = if (payload.get(0) and 128 === 0) "UTF-8" else "UTF-16" // Get the Text Encoding
var languageCodeLength: Int = payload.get(0) and 51  // Get the Language Code, e.g. "en"
Tim Pavone
  • 36
  • 1