Hi, I am a ruby newbie. I want to write a program which will scan a
input file, change every digital number into 4 bits len’s binary
number.
For example, for input.txt as
903
1047
I will get a new file as
100100000011
0001000001000111
Would anyboby kindly help to tell me how to do this?
I assume that by “4 bits len binary number” he means that he wants the
binary number to be a multiple of 4 characters long. So the binary
number
would have “0” prepended to it if the size wasn’t divisible by 4. Here
is
an overly verbose way to convert the num to the binary number string.
Hi ,thanks for advise.
I want my function to give output 100100000011 for input 903. Where
‘1001’,‘0000’,‘0011’ is the binary value for 9,0,3
Is there efficient way to do this?
Hi ,thanks for advise.
I want my function to give output 100100000011 for input 903. Where
‘1001’,‘0000’,‘0011’ is the binary value for 9,0,3
Is there efficient way to do this?
I don’t know about efficent, but you could start with something like
this and see if it’s performant enough:
irb(main):002:0> 903.to_s.split(“”).each {|digit| p digit.to_i.to_s(2)}
“1001”
“0”
“11”
Meh, actually, I bet someone else can do better than that, but I’m at
work right now. (:
Hi ,thanks for advise.
I want my function to give output 100100000011 for input 903. Where
‘1001’,‘0000’,‘0011’ is the binary value for 9,0,3
Is there efficient way to do this?
I want my function to give output 100100000011 for input 903. Where
‘1001’,‘0000’,‘0011’ is the binary value for 9,0,3
Is there efficient way to do this?
I want my function to give output 100100000011 for input 903. Where
‘1001’,‘0000’,‘0011’ is the binary value for 9,0,3
Is there efficient way to do this?
irb(main):002:0> 903.to_s.split(’’).map{|n| “%04b” % n }.to_s
=> “100100000011”
Had no idea that would work, but now it seems obvious… Apparently #Integer is being called by #% when the format char is ‘b’, because it
works correctly with different bases:
Hi ,thanks for advise.
I want my function to give output 100100000011 for input 903. Where
‘1001’,‘0000’,‘0011’ is the binary value for 9,0,3
Is there efficient way to do this?
Just for the record, that is commonly called BCD (for Binary Coded
Decimal).