Sorry to bump an old topic of mine, but I got sidetracked with work from
a different project and had one more question.
Joel VanderWerf wrote:
insert example code here
I’ve been using BitStruct and it works like a dream except in one area,
which is with strings. My first test class I am making keeps it easy by
putting it at the end of the packet so I can just use a rest field. And
although the output returned by description looks fine, when I convert
to a String for sending, the string is added on as is instead of
converted like all the other data. Here was the test code I wrote:
test_ascii_message.rb
require ‘bit-struct’
class TestAsciiMessage < BitStruct
unsigned :message_length, 48, “Message Length”, :endian => :network
unsigned :message_id, 28, “Unique Message ID”, :endian => :network
unsigned :service_id, 18, “Service Identifier”, :endian => :network
unsigned :event_id, 18, “Event Identifier”, :endian => :network
rest :text_msg, “Null terminated ASCII Message String”
end
main.rb
require ‘test_ascii_message’
test_packet = TestAsciiMessage.new
test_packet.message_id = 0
test_packet.service_id = 2
test_packet.event_id = 3
test_packet.text_msg = “Testing 01 10 11”
test_packet.message_length = test_packet.length
puts “-”*75
puts test_packet.inspect
puts “-”*75
puts test_packet.inspect_detailed
puts “-”*75
puts TestAsciiMessage.describe
puts “-”*75
p test_packet.to_s
And the resulting output was this:
#
TestAsciiMessage:
Message Length = 24
Unique Message ID = 0
Service Identifier = 2
Event Identifier = 3
Null terminated ASCII Message String = “Testing 01 10 11”
byte: type name [size] description
@0: unsigned message_length[ 32b] Message Length
@4: unsigned message_id [ 16b] Unique Message ID
@6: unsigned service_id [ 8b] Service Identifier
@7: unsigned event_id [ 8b] Event Identifier
“\000\000\000\030\000\000\002\003Testing 01 10 11”
This output is fine until it gets to the string. I just worry, like I
did above, because the program receiving this needs to see the string as
a null terminated *char string… did I say that right? Don’t know
enough C for this.
Anyways, that was my first question. The second question is how would I
go about converting a binary string I received into a BitStruct when
there is a variable length, null terminated string in the center of the
binary string? Figured I would ask since using a rest field won’t work
here.