Class: BinStruct::Int24

Inherits:
Int
  • Object
show all
Defined in:
lib/bin_struct/int.rb

Overview

3-byte unsigned integer

Author:

  • LemonTree55

Direct Known Subclasses

Int24be, Int24le, Int24n

Instance Attribute Summary

Attributes inherited from Int

#default, #endian, #value, #width

Instance Method Summary collapse

Methods inherited from Int

#format_inspect, #from_human, #nbits, #sz, #to_f, #to_i

Methods included from Structable

#format_inspect, #sz, #to_human, #type_name

Constructor Details

#initialize(options = {}) ⇒ Int24

Returns a new instance of Int24.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :value (Integer, nil)
  • :endian (:big, :little, :native)


239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/bin_struct/int.rb', line 239

def initialize(options = {})
  opts = options.slice(:value, :endian)
  opts[:endian] ||= :big
  opts[:width] = 3

  if opts[:endian] == :native
    opts[:endian] = if [1].pack('S').unpack1('n') == 1
                      :big
                    else
                      :little
                    end
  end
  super(opts)
end

Instance Method Details

#read(value) ⇒ self

Read a 3-byte Int from a binary string

Parameters:

  • value (::String)

Returns:

  • (self)


257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/bin_struct/int.rb', line 257

def read(value)
  return self if value.nil?

  up8 = down16 = 0
  if @endian == :big
    up8, down16 = value.to_s.unpack('Cn')
  else
    down16, up8 = value.to_s.unpack('vC')
  end
  @value = (up8 << 16) | down16
  self
end

#to_s::String

Returns:

  • (::String)

Author:

  • Sylvain Daubert (2016-2024)



272
273
274
275
276
277
278
279
280
# File 'lib/bin_struct/int.rb', line 272

def to_s
  up8 = to_i >> 16
  down16 = to_i & 0xffff
  if @endian == :big
    [up8, down16].pack('Cn')
  else
    [down16, up8].pack('vC')
  end
end