Page 1 of 1

How to parse unsigned short integer value from net-receive

Posted: Tue Jan 29, 2013 3:43 pm
by csfreebird
Hello
I know how to send unsigned short integer value with big-endian via TCP now.
But when trying to parse the unsigned short integer from bytes array returned by net-receive, I am stuck again.
Below is my codes, the server sends 3 bytes to client app written by newlisp.
The first byte is 0x01, the following two bytes are in big-endian, they represent one unsigned short integer here. I try to parse them using get-char twice. But it seems wrong.

Code: Select all

(define (receive-challenge-string socket)
  ;; receive head
  (unless (net-receive socket head 3) (quit-for-error))
  (unless (= (get-char (address head)) 1) (println "SOH in challenge message is wrong"))
  (println 
   (unpack ">u" (get-char (+ (address head) 1)) (get-char (+ (address head) 2)))
   ))

Re: How to parse unsigned short integer value from net-recei

Posted: Tue Jan 29, 2013 4:46 pm
by Lutz
Unless you need an offset into the buffer - head - received by 'net-receive', you don't need 'address' and when using 'unpack' you don't need 'get-char'.

Just do:

Code: Select all

> (set 'head (pack ">u" 123))
"\000{"
> (unpack ">u" head)   ; <--- this is all you need
(123)
> 

Re: How to parse unsigned short integer value from net-recei

Posted: Wed Jan 30, 2013 10:14 am
by csfreebird
Thank you lutz!
After removing get-char, I got the number 19 from server. Here are my correct codes below:

Code: Select all

(define (receive-challenge-string socket)
  ;; receive head
  (unless (net-receive socket head 3) (quit-for-error))
  (unless (= (get-char (address head)) 1) (println "SOH in challenge message is wrong"))
  (println (unpack ">u" (+ (address head) 1))))


Then it prints the correct number now:
(19)

Re: How to parse unsigned short integer value from net-recei

Posted: Wed Jan 30, 2013 3:09 pm
by Lutz
You could also unpack both numbers at once:

Code: Select all

> (set 'result (unpack ">cu" head))
(1 19)
> (unless (= (first result) 1) (println "SOH wrong"))
true
>