First time here? Check out the FAQ!

Ask Your Question
0

sage code for decimal to binary expansion

asked 8 years ago

this post is marked as community wiki

This post is a wiki. Anyone with karma >750 is welcome to improve it.

k=4 then (0100)

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
1

answered 8 years ago

kcrisman gravatar image

Interestingly, this hasn't been properly asked sometimes. Here is an example:

sage: a = 15
sage: a.binary()
'1111'
Preview: (hide)
link
1

answered 8 years ago

This gives the list of digits rather than a string:

sage: a = 14
sage: a.digits(2)
[0, 1, 1, 1]

Note that these are listed starting with the units digit.

Preview: (hide)
link

Comments

So in either case you have to do something... maybe b = a.digits(2); b.reverse() like this?

kcrisman gravatar imagekcrisman ( 8 years ago )

b = a.digits(2); b.reverse(); ''.join(map(str,b)) pretty much does the same thing as a.binary(). Doing this with other primitive data types can be done using the Python 'struct' package. For example, for floats: ''.join(bin(ord(c)).replace('0b', '').rjust(8, '0') for c in struct.pack('!f', num)). Anyone has any idea how to print the binary representation for Sage ring data types such as Rationals?

VivekGandhi gravatar imageVivekGandhi ( 5 years ago )

@VivekGandhi: what is the binary representation for a rational number? Is a.numerator().binary() + '/' + a.denominator().binary() what you mean? By the way, I don't think there can be a general answer for all "Sage ring data types," since they won't all have a meaningful binary representation.

John Palmieri gravatar imageJohn Palmieri ( 5 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 8 years ago

Seen: 10,327 times

Last updated: Dec 16 '16