Pack data into binary string

Hello,

I am trying to find a solution to pack data into a binary string similar to the pack function in php and perl. Specifically into unsigned short (always 16 bit, big endian byte order) format. I am trying to use it to write data to network socket so the big endian byte order is important. If someone could point me into the right direction I would appreciate it.

Thank you

Use https://sdkdocs.roku.com/display/sdkdoc/roByteArray , probably by using .push() (ifArray interface) on octets/bytes.
To chop into bytes, use bitwise ops and/or/<</>>

Hi RokuNB,
Thank you for the quick reply.
This is what I came up with based on a javascript implementation of the function

Function pack(value As Integer)
 result = ""
 result += chr(value >> 8 and 255)
 result += chr(value and 255)
 return result
End Function

For PHP the function pack(“n”, 333) will return a string “[SOH]M” where [SOH] is ascii symbol SOH. Roku will return “?M”
I am missing something and I can’t figure what.

Later edit: found my issue.
value >> 8 and 255 evaluates to 0 and chr(0) returns empty string if the specified value is 0 or an invalid Unicode value, as per the documentation. I need to preppend the ASCII 0 character, which is NUL. Any ideas how to do that?

ab = CreateObject("roByteArray")
ab.FromHexString("003C") 
?ab
aba = ab.ToAsciiString()
?type(aba)
?aba.len()

ba = CreateObject("roByteArray")
ba.push(0)
ba.push(60)
bab = ba.ToAsciiString()
?ba
?bab
?bab.len()

This will return

<Component: roByteArray> =
[
    0
    60
]
String
 0
<Component: roByteArray> =
[
    0
    60
]

 0

There is no way that I can see to obtain the 2 character string “[nul]<” that has the ascii codes 0060 or the hex code 003C. Does anybody have a workaround?

“kmikz” wrote:
[…]
There is no way that I can see to obtain the 2 character string “[nul]<” that has the ascii codes 0060 or the hex code 003C. Does anybody have a workaround?
If you start thinking of roByteArray as “binary string” (vs roString as “text string”), does that help?
Note how ifSocket .send/.receive() work with roByteArray and .sendStr/.receiveStr() work with texts…

Thank you, that was the solution I was looking for. My mistake was trying to do it like PHP and send string, I was not aware you could send byte arrays.