How to parse unsigned short integer value from net-receive

Started by csfreebird, January 29, 2013, 07:43:53 AM

Previous topic - Next topic

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.

(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)))
   ))

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:


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

csfreebird

Thank you lutz!

After removing get-char, I got the number 19 from server. Here are my correct codes below:

(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)

Lutz

You could also unpack both numbers at once:


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