|
Post by Josh on May 7, 2017 19:13:06 GMT
Characters to BinaryIn this challenge, you must write a program that takes the string "Hello, world!" and outputs the binary representation of it. To get the binary representation of a string, you should convert each character to it's ASCII value and then convert that into binary.
Example:
A -> 65 -> 01000001 B -> 66 -> 01000010 After, you should take each binary value and concatenate them separated by whitespace. The outputted string should look like:
01001000 01100101 01101100 01101100 01101111 00101100 00100000 01110111 01101111 01110010 01101100 01100100 00100001 Feel free to golf the code. If you are doing so, please post the length of your solution along with the language you wrote it in. Otherwise, just ensure that you post the language your solution is written in.
You are not allowed to hard-code your solution and your program must work offline.
Good luck!
|
|
|
Post by 128Gigabytes on May 7, 2017 20:00:55 GMT
153, Lua
a=''("Hello, world!"):gsub(".", function(b)c=b:byte()d=''e=128 for _=1,8 do if c-e>=0 then c=c-e d=d..1 else d=d..0 end e=e/2 end a=a..d.." "end)print(a)
|
|
|
Post by Josh on May 7, 2017 20:05:41 GMT
|
|
|
Post by 128Gigabytes on May 7, 2017 20:15:59 GMT
Here is an ungolfed one
local function tobinary(input)
local output = ''
for character in input:gmatch(".") do
local byte, x = string.byte(character), 128
for _ = 1, 8, 1 do
if ((byte - x) >= 0) then
byte, output = (byte - x), (output .. "1")
else
output = (output .. "0")
end
x = (x / 2)
end
output = (output .. " ")
end
return (output:sub(1, (#output - 1)));
end
print(tobinary("Hello, world!"))
|
|
|
Post by Josh on May 7, 2017 20:19:56 GMT
|
|