Converting BitSet to Byte[]












4















I have a BitSet, which needs to be converted to a Byte. However, by using BitSet.toByteArray(), I don't get the correct output. I have tried converting the Byte to its binary form in order to check whether the Bitset and the binary form of the Byte are similiar.



public static void generate() {

BitSet temp1 = new BitSet(64);

for (int i = 0; i < 64; i++) {
if(i % 8 != 0 && i < 23) {
temp1.set(i, true);
}
}

StringBuilder s = new StringBuilder();
for (int i = 0; i < 64; i++) {
s.append(temp1.get(i) == true ? 1 : 0);
}

System.out.println(s);

byte tempByteKey1 = temp1.toByteArray();

for (byte b : tempByteKey1) {
System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
}

}


Output:



Bitset: 0111111101111111011111100000000000000000000000000000000000000000
Converted Byte: 1111111011111110011111100000000000000000000000000000000000000000


They are both 64 bits, but the first 0 in the BitSet is placed somewhere else after the conversion. Why is this happening, and how can I fix it?










share|improve this question


















  • 1





    the bit order is being printed in reverse by toBinaryString as you are printing the BitSet. You start with the less significant bit, toBinaryString starts with the most significant one.(see how the zero is in first position on first output, and at 8th position on second output)

    – Carlos Heuberger
    Nov 20 '18 at 22:28













  • But they both have six trues as low order and seven trues as high order

    – user8231110
    Nov 20 '18 at 22:33






  • 1





    what are you counting??? BitSet: 01111111 01111111 01111110 0...; toBinaryString: 11111110 11111110 01111110 0... => each corresponding 8 bits are reversed. Or, using chars for bits, BitSet: hgfedcba ponmlkji ... , toBinaryString: abcdefgh ijklmnop ...

    – Carlos Heuberger
    Nov 20 '18 at 22:36













  • That makes sense, but is it possible to store it as it originally was i.e. without the reversing?

    – user8231110
    Nov 20 '18 at 22:40











  • ??? it is stored as originally , just the way you represent it differs as how toBinaryString does

    – Carlos Heuberger
    Nov 20 '18 at 22:40


















4















I have a BitSet, which needs to be converted to a Byte. However, by using BitSet.toByteArray(), I don't get the correct output. I have tried converting the Byte to its binary form in order to check whether the Bitset and the binary form of the Byte are similiar.



public static void generate() {

BitSet temp1 = new BitSet(64);

for (int i = 0; i < 64; i++) {
if(i % 8 != 0 && i < 23) {
temp1.set(i, true);
}
}

StringBuilder s = new StringBuilder();
for (int i = 0; i < 64; i++) {
s.append(temp1.get(i) == true ? 1 : 0);
}

System.out.println(s);

byte tempByteKey1 = temp1.toByteArray();

for (byte b : tempByteKey1) {
System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
}

}


Output:



Bitset: 0111111101111111011111100000000000000000000000000000000000000000
Converted Byte: 1111111011111110011111100000000000000000000000000000000000000000


They are both 64 bits, but the first 0 in the BitSet is placed somewhere else after the conversion. Why is this happening, and how can I fix it?










share|improve this question


















  • 1





    the bit order is being printed in reverse by toBinaryString as you are printing the BitSet. You start with the less significant bit, toBinaryString starts with the most significant one.(see how the zero is in first position on first output, and at 8th position on second output)

    – Carlos Heuberger
    Nov 20 '18 at 22:28













  • But they both have six trues as low order and seven trues as high order

    – user8231110
    Nov 20 '18 at 22:33






  • 1





    what are you counting??? BitSet: 01111111 01111111 01111110 0...; toBinaryString: 11111110 11111110 01111110 0... => each corresponding 8 bits are reversed. Or, using chars for bits, BitSet: hgfedcba ponmlkji ... , toBinaryString: abcdefgh ijklmnop ...

    – Carlos Heuberger
    Nov 20 '18 at 22:36













  • That makes sense, but is it possible to store it as it originally was i.e. without the reversing?

    – user8231110
    Nov 20 '18 at 22:40











  • ??? it is stored as originally , just the way you represent it differs as how toBinaryString does

    – Carlos Heuberger
    Nov 20 '18 at 22:40
















4












4








4








I have a BitSet, which needs to be converted to a Byte. However, by using BitSet.toByteArray(), I don't get the correct output. I have tried converting the Byte to its binary form in order to check whether the Bitset and the binary form of the Byte are similiar.



public static void generate() {

BitSet temp1 = new BitSet(64);

for (int i = 0; i < 64; i++) {
if(i % 8 != 0 && i < 23) {
temp1.set(i, true);
}
}

StringBuilder s = new StringBuilder();
for (int i = 0; i < 64; i++) {
s.append(temp1.get(i) == true ? 1 : 0);
}

System.out.println(s);

byte tempByteKey1 = temp1.toByteArray();

for (byte b : tempByteKey1) {
System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
}

}


Output:



Bitset: 0111111101111111011111100000000000000000000000000000000000000000
Converted Byte: 1111111011111110011111100000000000000000000000000000000000000000


They are both 64 bits, but the first 0 in the BitSet is placed somewhere else after the conversion. Why is this happening, and how can I fix it?










share|improve this question














I have a BitSet, which needs to be converted to a Byte. However, by using BitSet.toByteArray(), I don't get the correct output. I have tried converting the Byte to its binary form in order to check whether the Bitset and the binary form of the Byte are similiar.



public static void generate() {

BitSet temp1 = new BitSet(64);

for (int i = 0; i < 64; i++) {
if(i % 8 != 0 && i < 23) {
temp1.set(i, true);
}
}

StringBuilder s = new StringBuilder();
for (int i = 0; i < 64; i++) {
s.append(temp1.get(i) == true ? 1 : 0);
}

System.out.println(s);

byte tempByteKey1 = temp1.toByteArray();

for (byte b : tempByteKey1) {
System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
}

}


Output:



Bitset: 0111111101111111011111100000000000000000000000000000000000000000
Converted Byte: 1111111011111110011111100000000000000000000000000000000000000000


They are both 64 bits, but the first 0 in the BitSet is placed somewhere else after the conversion. Why is this happening, and how can I fix it?







java arrays bitset






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 22:17









user8231110user8231110

586




586








  • 1





    the bit order is being printed in reverse by toBinaryString as you are printing the BitSet. You start with the less significant bit, toBinaryString starts with the most significant one.(see how the zero is in first position on first output, and at 8th position on second output)

    – Carlos Heuberger
    Nov 20 '18 at 22:28













  • But they both have six trues as low order and seven trues as high order

    – user8231110
    Nov 20 '18 at 22:33






  • 1





    what are you counting??? BitSet: 01111111 01111111 01111110 0...; toBinaryString: 11111110 11111110 01111110 0... => each corresponding 8 bits are reversed. Or, using chars for bits, BitSet: hgfedcba ponmlkji ... , toBinaryString: abcdefgh ijklmnop ...

    – Carlos Heuberger
    Nov 20 '18 at 22:36













  • That makes sense, but is it possible to store it as it originally was i.e. without the reversing?

    – user8231110
    Nov 20 '18 at 22:40











  • ??? it is stored as originally , just the way you represent it differs as how toBinaryString does

    – Carlos Heuberger
    Nov 20 '18 at 22:40
















  • 1





    the bit order is being printed in reverse by toBinaryString as you are printing the BitSet. You start with the less significant bit, toBinaryString starts with the most significant one.(see how the zero is in first position on first output, and at 8th position on second output)

    – Carlos Heuberger
    Nov 20 '18 at 22:28













  • But they both have six trues as low order and seven trues as high order

    – user8231110
    Nov 20 '18 at 22:33






  • 1





    what are you counting??? BitSet: 01111111 01111111 01111110 0...; toBinaryString: 11111110 11111110 01111110 0... => each corresponding 8 bits are reversed. Or, using chars for bits, BitSet: hgfedcba ponmlkji ... , toBinaryString: abcdefgh ijklmnop ...

    – Carlos Heuberger
    Nov 20 '18 at 22:36













  • That makes sense, but is it possible to store it as it originally was i.e. without the reversing?

    – user8231110
    Nov 20 '18 at 22:40











  • ??? it is stored as originally , just the way you represent it differs as how toBinaryString does

    – Carlos Heuberger
    Nov 20 '18 at 22:40










1




1





the bit order is being printed in reverse by toBinaryString as you are printing the BitSet. You start with the less significant bit, toBinaryString starts with the most significant one.(see how the zero is in first position on first output, and at 8th position on second output)

– Carlos Heuberger
Nov 20 '18 at 22:28







the bit order is being printed in reverse by toBinaryString as you are printing the BitSet. You start with the less significant bit, toBinaryString starts with the most significant one.(see how the zero is in first position on first output, and at 8th position on second output)

– Carlos Heuberger
Nov 20 '18 at 22:28















But they both have six trues as low order and seven trues as high order

– user8231110
Nov 20 '18 at 22:33





But they both have six trues as low order and seven trues as high order

– user8231110
Nov 20 '18 at 22:33




1




1





what are you counting??? BitSet: 01111111 01111111 01111110 0...; toBinaryString: 11111110 11111110 01111110 0... => each corresponding 8 bits are reversed. Or, using chars for bits, BitSet: hgfedcba ponmlkji ... , toBinaryString: abcdefgh ijklmnop ...

– Carlos Heuberger
Nov 20 '18 at 22:36







what are you counting??? BitSet: 01111111 01111111 01111110 0...; toBinaryString: 11111110 11111110 01111110 0... => each corresponding 8 bits are reversed. Or, using chars for bits, BitSet: hgfedcba ponmlkji ... , toBinaryString: abcdefgh ijklmnop ...

– Carlos Heuberger
Nov 20 '18 at 22:36















That makes sense, but is it possible to store it as it originally was i.e. without the reversing?

– user8231110
Nov 20 '18 at 22:40





That makes sense, but is it possible to store it as it originally was i.e. without the reversing?

– user8231110
Nov 20 '18 at 22:40













??? it is stored as originally , just the way you represent it differs as how toBinaryString does

– Carlos Heuberger
Nov 20 '18 at 22:40







??? it is stored as originally , just the way you represent it differs as how toBinaryString does

– Carlos Heuberger
Nov 20 '18 at 22:40














1 Answer
1






active

oldest

votes


















1














From BitSet#toByteArray() javadoc:




Returns a new byte array containing all the bits in this bit set.
More precisely, if..




byte bytes = s.toByteArray();



then




bytes.length == (s.length()+7)/8



and




s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)



for all n < 8 * bytes.length.



@return a byte array containing a little-endian representation of all the bits in this bit set



@since 1.7




Attention: toByteArray() doesn't even claim to know size(), it is only "reliable" regarding length()!





..So I would propose as implementation (alternative for your toBinaryString()) a method like:



static String toBinaryString(byte barr, int size) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < 8 * barr.length; i++) {
sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
}
for (; i < size; i++) {
sb.append('0');
}
return sb.toString();
}


..to call it like:



System.out.println(toBinaryString(bitSet.toByteArray(), 64);




run:
0111111101111111011111100000000000000000000000000000000000000000
0111111101111111011111100000000000000000000000000000000000000000
BUILD SUCCESSFUL (total time: 0 seconds)





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%2f53402433%2fconverting-bitset-to-byte%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









    1














    From BitSet#toByteArray() javadoc:




    Returns a new byte array containing all the bits in this bit set.
    More precisely, if..




    byte bytes = s.toByteArray();



    then




    bytes.length == (s.length()+7)/8



    and




    s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)



    for all n < 8 * bytes.length.



    @return a byte array containing a little-endian representation of all the bits in this bit set



    @since 1.7




    Attention: toByteArray() doesn't even claim to know size(), it is only "reliable" regarding length()!





    ..So I would propose as implementation (alternative for your toBinaryString()) a method like:



    static String toBinaryString(byte barr, int size) {
    StringBuilder sb = new StringBuilder();
    int i = 0;
    for (; i < 8 * barr.length; i++) {
    sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
    }
    for (; i < size; i++) {
    sb.append('0');
    }
    return sb.toString();
    }


    ..to call it like:



    System.out.println(toBinaryString(bitSet.toByteArray(), 64);




    run:
    0111111101111111011111100000000000000000000000000000000000000000
    0111111101111111011111100000000000000000000000000000000000000000
    BUILD SUCCESSFUL (total time: 0 seconds)





    share|improve this answer






























      1














      From BitSet#toByteArray() javadoc:




      Returns a new byte array containing all the bits in this bit set.
      More precisely, if..




      byte bytes = s.toByteArray();



      then




      bytes.length == (s.length()+7)/8



      and




      s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)



      for all n < 8 * bytes.length.



      @return a byte array containing a little-endian representation of all the bits in this bit set



      @since 1.7




      Attention: toByteArray() doesn't even claim to know size(), it is only "reliable" regarding length()!





      ..So I would propose as implementation (alternative for your toBinaryString()) a method like:



      static String toBinaryString(byte barr, int size) {
      StringBuilder sb = new StringBuilder();
      int i = 0;
      for (; i < 8 * barr.length; i++) {
      sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
      }
      for (; i < size; i++) {
      sb.append('0');
      }
      return sb.toString();
      }


      ..to call it like:



      System.out.println(toBinaryString(bitSet.toByteArray(), 64);




      run:
      0111111101111111011111100000000000000000000000000000000000000000
      0111111101111111011111100000000000000000000000000000000000000000
      BUILD SUCCESSFUL (total time: 0 seconds)





      share|improve this answer




























        1












        1








        1







        From BitSet#toByteArray() javadoc:




        Returns a new byte array containing all the bits in this bit set.
        More precisely, if..




        byte bytes = s.toByteArray();



        then




        bytes.length == (s.length()+7)/8



        and




        s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)



        for all n < 8 * bytes.length.



        @return a byte array containing a little-endian representation of all the bits in this bit set



        @since 1.7




        Attention: toByteArray() doesn't even claim to know size(), it is only "reliable" regarding length()!





        ..So I would propose as implementation (alternative for your toBinaryString()) a method like:



        static String toBinaryString(byte barr, int size) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (; i < 8 * barr.length; i++) {
        sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
        }
        for (; i < size; i++) {
        sb.append('0');
        }
        return sb.toString();
        }


        ..to call it like:



        System.out.println(toBinaryString(bitSet.toByteArray(), 64);




        run:
        0111111101111111011111100000000000000000000000000000000000000000
        0111111101111111011111100000000000000000000000000000000000000000
        BUILD SUCCESSFUL (total time: 0 seconds)





        share|improve this answer















        From BitSet#toByteArray() javadoc:




        Returns a new byte array containing all the bits in this bit set.
        More precisely, if..




        byte bytes = s.toByteArray();



        then




        bytes.length == (s.length()+7)/8



        and




        s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)



        for all n < 8 * bytes.length.



        @return a byte array containing a little-endian representation of all the bits in this bit set



        @since 1.7




        Attention: toByteArray() doesn't even claim to know size(), it is only "reliable" regarding length()!





        ..So I would propose as implementation (alternative for your toBinaryString()) a method like:



        static String toBinaryString(byte barr, int size) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        for (; i < 8 * barr.length; i++) {
        sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
        }
        for (; i < size; i++) {
        sb.append('0');
        }
        return sb.toString();
        }


        ..to call it like:



        System.out.println(toBinaryString(bitSet.toByteArray(), 64);




        run:
        0111111101111111011111100000000000000000000000000000000000000000
        0111111101111111011111100000000000000000000000000000000000000000
        BUILD SUCCESSFUL (total time: 0 seconds)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Feb 10 at 8:03

























        answered Feb 6 at 12:28









        xerx593xerx593

        3,56921534




        3,56921534
































            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%2f53402433%2fconverting-bitset-to-byte%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







            這個網誌中的熱門文章

            Hercules Kyvelos

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud