tags:

views:

57

answers:

1

I have a byte buffer 6 bytes long first four contains ip address last 2 contains port, in big endian notation.

to get the ip i am using,

(apply str (interleave (map int (take 4 peer)) (repeat ".")))

Is casting bytes to int safe to get the ip address?

and also in java i use,

    int port = 0;
    port |= peerList[i+4] & 0xFF;
    port <<= 8;
    port |= peerList[i+5] & 0xFF;

this snippet to get the port address. How can i convert this to clojure?

+2  A: 

yes mapping them to should be safe in this case because any leading zeros that are intoduced by writing into a larger data type will drop away again when it is converted into a string

The second part gets a lot easier because you are starting with a list of bytes.

(+ (* 256 (nth 5 peer)) (nth 4 peer))

A more general function for turning lists of bytes into numbers pulled from here

(defn bytes-to-num [bytes] 
     (let [powers (iterate #(* % 256) 1)]
       (reduce + 0 (map * bytes powers))))
Arthur Ulfeldt