in reply to question of pack.
why we need to add a 'pack/unpack' behavior while transfering data?
When the data is sent over a stream (e.g. a TCP socket), the reader has no way of knowing where the data ends.
For example, if I told you "THE FOX IS BROWN", would you know if my sentence is done? If I continued with "AND FAST", is it part of this sentence, or is it the start of another?
One solution is to use a terminal (the period of a sentence, for example) to mark the end of the data. Another solution is to prepend the data with its length (as in your code snippet).
How do I convert decimal to hex,oct,bin or others? or I should use sprintf?
For starters, the number is not stored in base 10. 255, 0xFF, 250+5 are all stored identically, so calling your number a "decimal" is wrong unless you mean it's not an integer.
"Converting a number to hex/oct/bin" and "Formatting a number as hex/oct/bin" are short ways of saying "getting the string representation of a number in hex/oct/bin". sprintf is all about formatting numbers, so it's a very appropriate function to use. Other means can probably be used, but they won't be as readable.
|
|---|