Last active
August 29, 2015 14:08
-
-
Save kvendrik/84c3af5b3f4f9dbbf28d to your computer and use it in GitHub Desktop.
Simple Binary - Text converter (Ruby practise)(Can be done more easily using Ruby's `pack` and `unpack`)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinaryText | |
@eight_bit_nums = [128, 64, 32, 16, 8, 4, 2, 1] | |
def self.binaryToText(binary) | |
groups = binary.scan(/.{8}/) | |
resultStr = '' | |
# loop through groups of 8 | |
groups.each do |group| | |
result = 0 | |
# loop through nums in group | |
group.each_char.with_index do |bool, idx| | |
if bool.to_i == 1 | |
result += @eight_bit_nums[idx] | |
end | |
end | |
resultStr += result.chr | |
end | |
return resultStr | |
end | |
def self.textToBinary(text) | |
resultBin = '' | |
text.each_byte do |char_code| | |
group = '' | |
remains = char_code | |
@eight_bit_nums.each do |num| | |
if remains / num > 0 | |
# remains fits in curr number | |
remains -= num | |
group += '1' | |
else | |
# remains doesn't fit in curr number | |
group += '0' | |
end | |
end | |
resultBin += group | |
end | |
return resultBin | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment