1

I want to extract all 0s between two 1s and group them from a binary number. So far I've done this,

529.to_s(2).scan(/1(0+)1/)

the output is array with one element only, although i want two elements. That is

529 => binary => 1000010001

["0000","000"]
1
  • From the answer you have accepted, it seems you only wanted zeros from a binary number, whether they are surrounded by ones doesn't seem to matter. If you only wanted zeros, why didn't you try 529.to_s(2).scan /0+/ matches one or more zeros regardless of the presence of ones. In any case, a binary number contains only zeros and ones. So the only other thing zeros could be surrounded is ones. Commented Sep 8, 2013 at 12:42

3 Answers 3

2
529.to_s(2).scan(/(?<=1)0+(?=1)/)
# => ["0000", "000"]
Sign up to request clarification or add additional context in comments.

Comments

0

How is this ?

a = 529.to_s(2).split("1")
a.delete("")
a # => ["0000", "000"]

6 Comments

You could write that as 529.to_s(2).scan /0+/. Not sure whether OP really wanted that.
@bsd He wants - I want to extract all 0s between two 1s :)
Try it out with numbers like 8, 4, 2, 14. See if the zeros are really surrounded by ones.
@bsd a = 8.to_s(2).split("1") # => ["", "000"] I got.
But where is the second one in 1000. There is only one one.
|
0

all 0s between two 1s and group

So I presume you don't want matches like 10, 100, 111000, 1000 and so on. The easiest way is to find the left and right index of the first one from the start and end and then start looking only for zeros.

Here is one way.

bin=8.to_s(2) #=> 1000
bin[bin.index('1')..bin.rindex('1')].scan /0+/
#=> []

bin=529.to_s(2) #=> 1000
bin[bin.index('1')..bin.rindex('1')].scan /0+/
#=> ["0000", "000"]

Beware of 0. It does not contains any one and you get nil.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.