I have a plain textfile consisting of 4M numbers (0 and 1's) from the number Pi. I would like to split this textfile into blocks of 8 bits (ie 8 characters). I know this can be done with StringTake but my knowledge is too little. Can anyone please help. Thanks in advance.

  • 2
    $\begingroup$ look up StringPartition in the docs. $\endgroup$
    – kglr
    Feb 17, 2019 at 12:13

2 Answers 2


You can use StringPartition["string",n] to partition the input string into nonoverlapping substrings of length n:

StringPartition[ExampleData[{"Text", "Prufrock"}], 24] // Column

enter image description here


You can read the file 8 characters at a time. Try this code:

pistream = OpenRead["pibinary.txt"] (* use your file name instead *)

to open up a stream of data. You can read in $8$ characters at a time with

ClearAll[c, s]; c = 0; While[ 
  8 == Length[s[c+1] = Read[pistream, Table[Character, {8}]]], c++];

and do what you want with the characters read. Here s[1], s[2], ..., s[c] are lists of $8$ characters each read from the file. This approach is probably too bulky for the large file you have.

Alternatively, you can read the entire text file as a string and then split it. Try this code:

pistring = ReadList["pibinary.txt", Record, RecordSeparators -> {}][[1]];
pistring8 = StringPartition[pistring, 8];

Here pistring8[[1]], pistring8[[2]], ... are the $8$ character strings from the file. If you want to turn these $8$ character strings into lists of $8$ characters you can use Characters@pistring8[[n]] or else StringPartition@pistring8[[n]].

Of course, this asssumes that the only characters in the file are "0" and "1". If there are newlines or space characters, then the code needs some adjustment.

Note that you can always display lists of lists of characters as a matrix using something like

Table[s[n], {n, 8}] // MatrixForm
  • $\begingroup$ This really helped me out, it proved my theory. One more question: how can I list the first 8 sc[] groups in one time? I mean that i have the first 64 bits listed in 8 sequences of 8 bits? thus sc[1] until sc[8] listed in for example a matrix?. $\endgroup$ Feb 19, 2019 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.