Question
· Sep 3, 2020

How to handle raw byte data naturally

I  have java  language experence. If I need parse a binary tcp packet . like following format

encoded string and send it to peer by tcp

1byte msg type + 4 byte(unsigned int) + raw byte(body)

To parse this package , Some Java code like this:

byte[] data = new byte[1024];

Bytebuf buf  = new ByteBuf(data)

byte type = buf.read()

int len = buf.ReadInt()

byte[] bodyBuff = new byte[len]

buf.Read(bodyBuff)

String str = new String(strBody)

So, does Objectscript have similar functionality to achieve similar results?

Tks.

Discussion (1)0
Log in or sign up to continue

let's have  your  binary  input in variable data 

JAVA                                  ObjectScript
byte[] data = new byte[1024];                                            ;
Bytebuf buf  = new ByteBuf(data)      set buf=data              ; make your work copy  
byte type = buf.read()                set type=$extract(buf)    ; if type = character 
                                      set type=$ascii(buf)      ; if type = binary
int len = buf.ReadInt()               set len=$zlascii($extract(buf,2,5))           ; if order low->high
                                      set len=$zlascii($reverse($extract(buf,2,5))) ; li order high->low
 
byte[] bodyBuff = new byte[len]       
buf.Read(bodyBuff)                    
String str = new String(strBody)      set str=$extract(buf,6,*) ; take rest of buf


from the description there are 2 open points:

  • is type a binary value or a character   
  • for length it could be
  • -         low byte first   so 515  => x/02 03 00 00  ;  default
  • -  or high byte first  so  515 => x/00 00 02 03   ;  need to reverse order

therefore I have added both variants