mikkar15
(Mikael K)
1
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
jfriedman
(Jesse Friedman)
2
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!
mikkar15
(Mikael K)
3
Thanks a lot, it works well!
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"
mikkar15
(Mikael K)
5
Oh, IntegerString function takes 3 arguments!
Yes, that’s exactly what i was looking for.
Thank you.
jfriedman
(Jesse Friedman)
6
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.