how to get all the positions of the set bits of a binary string in java? -


for example if binary string 10100010 program must return 1st,3rd , 7th i.e positions of 1's.

two options:

  1. convert integer/long (if possible) , shift 1 bit each time , check if it's 1. example:

    string str = "10100010"; integer x = integer.valueof(str); int len = str.length(); while (x != 0) {     if (x & 0x1 == 1) {         system.out.println(len);     }     len--;     x >>= 1; } 
  2. scan string by-index , check if its' value 1:

    for (int = 0; < str.length(); i++) {     if (str.chatat(i) == '1') {         //print     } } 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -