Skip to content

Instantly share code, notes, and snippets.

@rhwlo
Last active April 16, 2017 04:21
Show Gist options
  • Save rhwlo/309806b5891d150a6eb9c0dc57301270 to your computer and use it in GitHub Desktop.
Save rhwlo/309806b5891d150a6eb9c0dc57301270 to your computer and use it in GitHub Desktop.
# invoke with, ex., 'echo "10010 10110" | sed -rf adder.sed'
:add
p
# If we have two final zeroes:
/^[01]*0\s[01]*0$/ {
# drop the final zeroes
s/^([01]*)0(\s)([01]*)0$/\1\2\3/
# swap the hold buffer in
x
# add a 0 at the front
s/^/0/
p; x; /[01]+/ b add
}
# If we have one final one:
/^([01]*0\s[01]*1|[01]*1\s[01]*0)$/ {
# drop the final digits
s/^([01]*).(\s)([01]*).$/\1\2\3/
# swap the hold buffer in
x
# add a 1 at the front
s/^/1/
p; x; /[01]+/ b add
}
# If we have two final ones:
/^[01]*1\s[01]*1$/ {
# drop the final digits
s/^([01]*)1(\s)([01]*)1$/\1\2\3/
# swap the hold buffer in and add a C (for Carry)
x
s/^/C/
p; x; /[01]+/ b add
}
/^\s*[01]+\s*$/ {
# prepend the pattern buffer to the hold buffer
x; H
# remove the spaces
x; s/\s*//g
p; x; /[01]+/ b add
}
/[01]+/! x
:carry
s/(^|0)C/10/g
s/1C/C0/g
p
/C/ b carry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment