Converting StringMonoidElement to Integer

467 views
Skip to first unread message

duro

unread,
Oct 16, 2010, 8:39:21 AM10/16/10
to sage-support
Hello.

Is there a possibility to convert type <class
'sage.monoids.string_monoid_element.StringMonoidElement'> to Integer
in efficient way? I've generated some random bits by calling
blum_blum_shub(length,lbound,ubound) but I need the binary result (or
rather the StringMonoidElement) to be represented as a decimal number.

Regards,
duro
Message has been deleted

duro

unread,
Oct 16, 2010, 10:02:08 AM10/16/10
to sage-support
So obvious! Thanks Minh for pointing it out to me. In the meantime
I've written a function that does the same but it was very inefficent.

Regards,
duro


> Yes, there two ways to do what you want.
>
> > I've generated some random bits by calling
> > blum_blum_shub(length,lbound,ubound) but I need the binary result (or
> > rather the StringMonoidElement) to be represented as a decimal number.
>
> Here are two ways, assuming that you want the bits in little-endian
> order, i.e. you read the bits from right to left in increasing order
> of powers of 2.
>
> sage: version()
> 'Sage Version 4.5.3, Release Date: 2010-09-04'
> sage: from sage.crypto.stream import blum_blum_shub
> sage: b = blum_blum_shub(length=6, lbound=10**4, ubound=10**5); b
> 100110
> sage: type(b)
> <class 'sage.monoids.string_monoid_element.StringMonoidElement'>
> sage: # read in little-endian order
> sage: # conversion using Python's built-in int()
> sage: int(str(b), base=2)
> 38
> sage: # conversion using Sage's built-in Integer()
> sage: Integer(str(b), base=2)
> 38
>
> Now assume you read the bitstring as output by blum_blum_shub() in
> big-endian order, i.e. from left to right in increasing order of
> powers of 2. You simply convert the bitstring to a string, reverse
> that string, and apply any of the above two methods.
>
> sage: # reversing a string
> sage: str(b)
> '100110'
> sage: str(b)[::-1]
> '011001'
> sage: # read in big-endian order
> sage: int(str(b)[::-1], base=2)
> 25
> sage: Integer(str(b)[::-1], base=2)
> 25
>
> --
> Regards
> Minh Van Nguyen
Message has been deleted

duro

unread,
Oct 16, 2010, 2:50:35 PM10/16/10
to sage-support
The main idea was the same, but I've implemented it in a different
manner ;)

Regards,
duro

On 16 Paź, 16:14, Minh Nguyen <nguyenmi...@gmail.com> wrote:
> Hi duro,
>
> On Sun, Oct 17, 2010 at 1:02 AM, duro <hereweg...@gmail.com> wrote:
> > So obvious! Thanks Minh for pointing it out to me.
>
> No worries.
>
> > In the meantime
> > I've written a function that does the same but it was very inefficent.
>
> You mean something like the following?
>
> sage: b = "100110"
> sage: sum(Integer(i) * (2^Integer(e)) for e, i in enumerate(b))
> 25
> sage:
> sage: sum(Integer(i) * (2^Integer(e)) for e, i in enumerate(b[::-1]))
> 38
Reply all
Reply to author
Forward
0 new messages