Message Boards Message Boards

0
|
4122 Views
|
5 Replies
|
3 Total Likes
View groups...
Share
Share this post:
GROUPS:

Wolfram Mathematica truncates initial 0:s

Posted 9 years ago

I'm trying to convert a list with numbers into a string with binary values.

In[168]:= x={10, 10};

IntegerString[x,2]

z=StringJoin[IntegerString[x,2]]

Out[169]= {1010,1010}

Out[170]= 10101010

The desired result would be:

Out[169]= {0001010, 0001010}

Out[170]= 00010100001010

POSTED BY: Mikael K
5 Replies
Posted 9 years ago

Isn't this what you are looking for?

In[10]:= x = {10, 10};

IntegerString[x, 2, 7]

z = StringJoin[IntegerString[x, 2, 7]]

Out[11]= {"0001010", "0001010"}

Out[12]= "00010100001010"
POSTED BY: Bill Simpson
Posted 9 years ago

Oh, IntegerString function takes 3 arguments!

Yes, that's exactly what i was looking for.

Thank you.

POSTED BY: Mikael K

Bill's solution certainly works if all of your values are below 256, but if any are greater it improperly truncates them:

In[1]:= x = {10, 256};

In[2]:= IntegerString[x, 2, 8]

Out[2]= {"00001010", "00000000"}

In[3]:= padBase2Strings[IntegerString[x, 2]]

Out[3]= {"00001010", "0000000100000000"}

Note this detail from the documentation on the third argument, len:

If len is less than the number of digits in n, then the len least significant digits are returned.

POSTED BY: Jesse Friedman

I've had this problem in the past. Here's my solution:

padBase2Strings[s_List] := 
 StringPadLeft[#, Ceiling[StringLength[#], 8], "0"] & /@ s

padBase2Strings[IntegerString[{10, 10}, 2]]

Out[1]= {"00001010", "00001010"}

StringJoin[padBase2Strings[IntegerString[{10, 10}, 2]]]

Out[2]= "0000101000001010"

I seem to recall having found a better solution, but I don't remember what it was!

POSTED BY: Jesse Friedman
Posted 9 years ago

Thanks a lot, it works well!

POSTED BY: Mikael K
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract