2

I have a long binary string that I would like to split every 32 characters. Is there a command that can do this for me?

I have tried word wrapping, but it splits per word. It has no effect since a binary string without spaces is considered 'one word'.

For example, turn this:

0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Into this:

00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000
6

For occasional use, you can do with query-replace-regexp (C-M-%).

Replace .\{32\} with \&^J. This means, replace all chunks of 32 characters, with the same thing followed by a newline. To type the newline into the replacemnt, use C-q C-j.

If you want to apply this only to binary strings, use [01]\{32\} for matching. This will protect other text from being split.

0

You can split the string every 32 characters, adding them to a list:

(defun split-string-every (string chars)
  "Split STRING into substrings of length CHARS characters.

This returns a list of strings."
  (cond ((string-empty-p string)
         nil)
        ((< (length string)
            chars)
         (list string))
    (t (cons (substring string 0 chars)
             (split-string-every (substring string chars)
                                 chars)))))

Some tests for the code are here:

(ert-deftest split-string-every/basic ()
  (should (equal '("12" "34" "56" "78" "90")
                 (split-string-every "1234567890" 2))))

(ert-deftest split-string-every/with-trailing-single-character ()
  (should (equal '("12" "34" "56" "78" "90" "a")
                 (split-string-every "1234567890a" 2))))

And if you need to end up with a string, you can call #'string-join on the result:

ELISP> (string-join (split-string-every "1234567890" 2) "\n")
"12\n34\n56\n78\n90"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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