How to parse unsigned short integer value from net-receive

Q&A's, tips, howto's
Locked
csfreebird
Posts: 107
Joined: Tue Jan 15, 2013 11:54 am
Location: China, Beijing
Contact:

How to parse unsigned short integer value from net-receive

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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

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

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

csfreebird
Posts: 107
Joined: Tue Jan 15, 2013 11:54 am
Location: China, Beijing
Contact:

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

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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

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

Post 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
> 

Locked