Ask Your Question
1

How to convert an integer to fixed length binary string in Sage?

asked 2018-10-11 15:20:46 +0200

I want to get

(192,14,100)=>8bit binary of 192 || 8bit binary of 14 ||8bit binary of 100 => 110000000000111001100100 => 12586596 (equivalent decimal of the 24bits binary sting).

I have written python code to do this, but this code does not work in sage. Here is the code :

L=(192,14,100)
a=0
for i in range(3):
    a=(a << 8) ^ (L[i])
print a
print bin(a)

What is the best way to do so in Sage?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2018-10-11 16:11:24 +0200

eric_g gravatar image

Sage's preparser (*) turns ^ into the exponentiation symbol (**), in order to follow standard math notations:

sage: preparse("a=(a << 8) ^ (L[i])")
'a=(a << Integer(8)) ** (L[i])'

To enforce the original (Python) xor behavior, use ^^ instead of ^:

for i in range(3):
    a=(a << 8) ^^ (L[i])

(*) see the answer to this question.

edit flag offensive delete link more

Comments

@eric_g I appreciate your answer. It woks fine.

BSFU gravatar imageBSFU ( 2018-10-11 16:41:08 +0200 )edit

sage: N(bin(round(pi*10^16)),digits=15) 3.14159265358979e16 But it looks answer is not in binary though.

jarkky gravatar imagejarkky ( 2022-04-08 15:46:41 +0200 )edit

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: 2018-10-11 15:20:46 +0200

Seen: 2,677 times

Last updated: Oct 11 '18