Class: Fixnum
- Inherits:
-
Object
- Object
- Fixnum
- Defined in:
- lib/bitlab.rb
Overview
RubyLabs
Instance Method Summary collapse
-
#code(*args) ⇒ Object
Create a Code object showing the binary or hexadecimal representation of this number.
Instance Method Details
#code(*args) ⇒ Object
Create a Code object showing the binary or hexadecimal representation of this number. The two arguments, both optional, define the type of representation and the number of digits:
x.code make a binary code for x, using as many bits as necessary
x.code(n) make a binary code for x, using n bits
x.code(:hex) make a hex code for x, using as many digits as necessary
x.code(:hex,n) make a hex code for x, using n digits (i.e. 4*n bits)
Example:
>> x = 26
=> 26
>> x.code
=> 11010
>> x.code(8)
=> 00011010
>> x.code(:hex)
=> 1A
>> x.code(:hex, 3)
=> 01A
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 |
# File 'lib/bitlab.rb', line 1019 def code(*args) if args.first == :hex base = args.shift else base = :binary end if args.first.kind_of? Integer digits = args.shift elsif args.empty? b = (self == 0) ? 1 : log2(self+1).ceil digits = (base == :hex) ? (b/4.0).ceil : b else raise "code: can't understand #{args}" end if base == :hex return HexCode.new(self, 4*digits) else return Code.new(self, digits) end # bits = (base == :hex) ? digits * 4 : digits # return Code.new(self, bits, base) end |