# Reading from a text file and store the results back into it

I am totally new to mathematica but started learning how to use it. I use the following function to convert a decimal number into its binary representation.

binExp[num_, d_] := First[RealDigits[N[num, d], 2]];


Currently, I am stuck with two points:

1. If I type binExp[240, 7], I get a 23-bit binary representation of a decimal number in the interval [0,255] BUT I need a 24-bit binary representation of it.

2. I have a 100,000 decimal numbers stored in a text file and want to use the previous function within mathematica to convert all of them to their 24-bit binary representation and store them back in a text file.

Any help is appreciated.

-
Fadi Abu-Amara, welcome to Stack Exchange Mathematica site! I have edited your question for it to conform with the standards of how questions are asked here (in particular, if you want to inlude your signature / contact information, best place to do that is in your user profile, not in the questions you ask). I hope you will find this site useful! –  Leonid Shifrin Feb 6 '12 at 12:43
...are your numbers integers or actual real numbers? –  Ｊ. Ｍ. Feb 6 '12 at 12:46
In your example you are trying to extract the first 24 bits of a number with precision 7 but since N[Log2[10^7]] is approximately 23.2535 you can only expect to find the first 23 digits this way. You would need a precision of at least Log10[2^24]. –  Heike Feb 6 '12 at 12:48
You need to include samples of both your input and desired output formats. As written your binExp function and use doesn't make a lot of sense. –  Mr.Wizard Feb 6 '12 at 18:36
Is this what you want? be[num_] := RealDigits[num, 2, 24]; –  Rolf Mertig Feb 6 '12 at 19:00

I'm new to Mathematica too, and finding some of it quite difficult, etc. However, the Import and Export commands seem to be pretty useful and simple for simple tasks.

To import a text file of numbers, one to a line, you basically do this:

aList = Import["test,dat", "Table"]


where the Table option reads the file into a list of lists, where each line is a list. So you might end up with something like this:

{{42}, {142857}, {6}, {12}}


This is then easy to operate on. Mathematica has functions for nearly everything, and lists are about the best thing to put your data in, so you can just write your own wrapper function:

numberToBinary[n_] :=  IntegerString[n, 2, 24];


Finally, you can export the numbers and convert them all in one go, by mapping this function over the list you created earlier:

Export["test1.dat", numberToBinary[#] &  /@ aList, "Table"]


and the file might well contain this:

000000000000000000101010
000000100010111000001001
000000000000000000000110
000000000000000000001100


It's true that things are rarely as simple as this, but it's a start... (And performance for 100,000 numbers might be important, I didn't check.)

-