Converting Java bitwise “and” operator over to Kotlin












3















I have a an array of bytes I'm calculating a checksum for in Java. And I'm trying to convert it to Kotlin. But the problem is that I am getting different values when calculating the -128 & 0xff in Java than it's equivalent in Kotlin. When passing in the -128, when I make the calculation in Java, it gives me a positive 128, but when I run it in Kotlin, it gives me a -128.



public class Bytes {

public static byte getByteArray() {
return new byte {-128};
}

public static int getJavaChecksum() {
int checksum = 0;

for (Byte b : getByteArray()) {
checksum += (b & 0xff);
}

return checksum;
}
}


This is my Kotlin code. I'm calling into the above bytes class to get the "byte array" I'm working with. So both pieces are running on the same input.



fun getKotlinChecksum(array: ByteArray): Byte {
var checksum = 0
for (b in array) {
checksum += (b and 0xFF.toByte())
}
return checksum.toByte()
}

fun main(args: Array<String>) {

println(Bytes.getJavaChecksum())
print(getKotlinChecksum(Bytes.getByteArray()))
}


The Java code is from a legacy code base that uses I2C to send over these bytes to a microcontroller. Is the Java just wrong? Or is there a way that I can get the 128 in the Kotlin code?










share|improve this question





























    3















    I have a an array of bytes I'm calculating a checksum for in Java. And I'm trying to convert it to Kotlin. But the problem is that I am getting different values when calculating the -128 & 0xff in Java than it's equivalent in Kotlin. When passing in the -128, when I make the calculation in Java, it gives me a positive 128, but when I run it in Kotlin, it gives me a -128.



    public class Bytes {

    public static byte getByteArray() {
    return new byte {-128};
    }

    public static int getJavaChecksum() {
    int checksum = 0;

    for (Byte b : getByteArray()) {
    checksum += (b & 0xff);
    }

    return checksum;
    }
    }


    This is my Kotlin code. I'm calling into the above bytes class to get the "byte array" I'm working with. So both pieces are running on the same input.



    fun getKotlinChecksum(array: ByteArray): Byte {
    var checksum = 0
    for (b in array) {
    checksum += (b and 0xFF.toByte())
    }
    return checksum.toByte()
    }

    fun main(args: Array<String>) {

    println(Bytes.getJavaChecksum())
    print(getKotlinChecksum(Bytes.getByteArray()))
    }


    The Java code is from a legacy code base that uses I2C to send over these bytes to a microcontroller. Is the Java just wrong? Or is there a way that I can get the 128 in the Kotlin code?










    share|improve this question



























      3












      3








      3








      I have a an array of bytes I'm calculating a checksum for in Java. And I'm trying to convert it to Kotlin. But the problem is that I am getting different values when calculating the -128 & 0xff in Java than it's equivalent in Kotlin. When passing in the -128, when I make the calculation in Java, it gives me a positive 128, but when I run it in Kotlin, it gives me a -128.



      public class Bytes {

      public static byte getByteArray() {
      return new byte {-128};
      }

      public static int getJavaChecksum() {
      int checksum = 0;

      for (Byte b : getByteArray()) {
      checksum += (b & 0xff);
      }

      return checksum;
      }
      }


      This is my Kotlin code. I'm calling into the above bytes class to get the "byte array" I'm working with. So both pieces are running on the same input.



      fun getKotlinChecksum(array: ByteArray): Byte {
      var checksum = 0
      for (b in array) {
      checksum += (b and 0xFF.toByte())
      }
      return checksum.toByte()
      }

      fun main(args: Array<String>) {

      println(Bytes.getJavaChecksum())
      print(getKotlinChecksum(Bytes.getByteArray()))
      }


      The Java code is from a legacy code base that uses I2C to send over these bytes to a microcontroller. Is the Java just wrong? Or is there a way that I can get the 128 in the Kotlin code?










      share|improve this question
















      I have a an array of bytes I'm calculating a checksum for in Java. And I'm trying to convert it to Kotlin. But the problem is that I am getting different values when calculating the -128 & 0xff in Java than it's equivalent in Kotlin. When passing in the -128, when I make the calculation in Java, it gives me a positive 128, but when I run it in Kotlin, it gives me a -128.



      public class Bytes {

      public static byte getByteArray() {
      return new byte {-128};
      }

      public static int getJavaChecksum() {
      int checksum = 0;

      for (Byte b : getByteArray()) {
      checksum += (b & 0xff);
      }

      return checksum;
      }
      }


      This is my Kotlin code. I'm calling into the above bytes class to get the "byte array" I'm working with. So both pieces are running on the same input.



      fun getKotlinChecksum(array: ByteArray): Byte {
      var checksum = 0
      for (b in array) {
      checksum += (b and 0xFF.toByte())
      }
      return checksum.toByte()
      }

      fun main(args: Array<String>) {

      println(Bytes.getJavaChecksum())
      print(getKotlinChecksum(Bytes.getByteArray()))
      }


      The Java code is from a legacy code base that uses I2C to send over these bytes to a microcontroller. Is the Java just wrong? Or is there a way that I can get the 128 in the Kotlin code?







      java kotlin bit-manipulation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 0:45







      Rafa

















      asked Nov 13 '18 at 0:12









      RafaRafa

      99911841




      99911841
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Returning a Byte means the function cannot return 128 no matter what, so that needs to be Int. The Java checksum does a "full" sum, not just the lowest byte of the sum. Similarly the bitwise AND cannot be done on bytes, that is useless, the sign extension (the AND with 0xFF is to remove the extended sign bits) would still happen. Then it could be written as a loop, Java style, but in Kotlin it probably makes more sense to write something like this:



          fun getKotlinChecksum(array: ByteArray): Int {
          return array.map({ it.toInt() and 0xFF }).sum()
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271952%2fconverting-java-bitwise-and-operator-over-to-kotlin%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Returning a Byte means the function cannot return 128 no matter what, so that needs to be Int. The Java checksum does a "full" sum, not just the lowest byte of the sum. Similarly the bitwise AND cannot be done on bytes, that is useless, the sign extension (the AND with 0xFF is to remove the extended sign bits) would still happen. Then it could be written as a loop, Java style, but in Kotlin it probably makes more sense to write something like this:



            fun getKotlinChecksum(array: ByteArray): Int {
            return array.map({ it.toInt() and 0xFF }).sum()
            }





            share|improve this answer




























              2














              Returning a Byte means the function cannot return 128 no matter what, so that needs to be Int. The Java checksum does a "full" sum, not just the lowest byte of the sum. Similarly the bitwise AND cannot be done on bytes, that is useless, the sign extension (the AND with 0xFF is to remove the extended sign bits) would still happen. Then it could be written as a loop, Java style, but in Kotlin it probably makes more sense to write something like this:



              fun getKotlinChecksum(array: ByteArray): Int {
              return array.map({ it.toInt() and 0xFF }).sum()
              }





              share|improve this answer


























                2












                2








                2







                Returning a Byte means the function cannot return 128 no matter what, so that needs to be Int. The Java checksum does a "full" sum, not just the lowest byte of the sum. Similarly the bitwise AND cannot be done on bytes, that is useless, the sign extension (the AND with 0xFF is to remove the extended sign bits) would still happen. Then it could be written as a loop, Java style, but in Kotlin it probably makes more sense to write something like this:



                fun getKotlinChecksum(array: ByteArray): Int {
                return array.map({ it.toInt() and 0xFF }).sum()
                }





                share|improve this answer













                Returning a Byte means the function cannot return 128 no matter what, so that needs to be Int. The Java checksum does a "full" sum, not just the lowest byte of the sum. Similarly the bitwise AND cannot be done on bytes, that is useless, the sign extension (the AND with 0xFF is to remove the extended sign bits) would still happen. Then it could be written as a loop, Java style, but in Kotlin it probably makes more sense to write something like this:



                fun getKotlinChecksum(array: ByteArray): Int {
                return array.map({ it.toInt() and 0xFF }).sum()
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 13 '18 at 0:53









                haroldharold

                41.3k357108




                41.3k357108






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271952%2fconverting-java-bitwise-and-operator-over-to-kotlin%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Lugert, Oklahoma