Skip to content

Instantly share code, notes, and snippets.

@kojix2
Last active June 12, 2021 14:23
Show Gist options
  • Save kojix2/3e99cc6bd1e780c7e511ce0a80f2b8dd to your computer and use it in GitHub Desktop.
Save kojix2/3e99cc6bd1e780c7e511ce0a80f2b8dd to your computer and use it in GitHub Desktop.
Convert binary data to DNA sequence
# b2dna.cr
# Convert binary data to DNA sequence
# kojix2
# echo "This is not a DNA sequence" | ./b2dna
BIT2BASE = {
0 => { 0 => 'A', 1 => 'C' },
1 => { 0 => 'G', 1 => 'T' }
}
while b = ARGF.read_byte
4.times do |i|
x1 = b.bit(i * 2)
x2 = b.bit(i * 2 + 1)
print BIT2BASE[x1][x2]
end
end
# dna2b.cr
# Convert binary data to DNA sequence
# kojix2
# echo "This is not a DNA sequence" | ./b2dna | ./dna2b
require "bit_array"
BASE2BIT = {
'A' => [false, false],
'C' => [false, true],
'G' => [true, false],
'T' => [true, true]
}
b_array = [] of Bool
while c = ARGF.read_char
b_array.concat BASE2BIT[c]
end
ba = BitArray.new(b_array.size)
b_array.each_with_index do |b, i|
ba[i] = b
end
STDOUT.write(ba.to_slice)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment