In your question, you stated that you want to convert user input from 175 to 00000000 00000000 00000000 10101111 , which is a large byte order of bytes, also known as network byte order.
Basically a portable way to convert your unsigned integer to an unsigned array of unsigned char, as you suggested from this example, β175β you specified will use the C htonl() function (defined in the header on Linux systems) to convert your unsigned int into the byte order of large endian, then use memcpy() (defined in the header <string.h> for C, <cstring> for C ++) to copy the bytes into your char (or unsigned char).
The htonl() function takes an unsigned 32-bit integer as an argument (unlike htons() , which takes an unsigned 16-bit integer) and converts it to the network byte order from the host byte order (hence the abbreviation, Host TO Network Long , against Host TO Network Short for htons ), returning the result as a 32-bit unsigned integer. The purpose of this family of functions is to ensure that all network communications are executed in large byte order, so that all machines can communicate with each other via a socket without problems with byte order. (Aside, for large-end machines, the htonl() , htons() , ntohl() and ntohs() are usually compiled to simply be "no op" because bytes do not need to be reversed before they are sent or received from socket, as they are already in the correct byte order)
Here is the code:
#include <stdio.h> #include <arpa/inet.h> #include <string.h> int main() { unsigned int number = 175; unsigned int number2 = htonl(number); char numberStr[4]; memcpy(numberStr, &number2, 4); printf("%x %x %x %x\n", numberStr[0], numberStr[1], numberStr[2], numberStr[3]); return 0; }
Note that, as caf said, you need to print characters as unsigned characters using the printf %x format specifier.
The above code prints 0 0 0 af on my machine (an x86_64 machine that uses a small ordinal number of bytes), which is hexadecimal for 175.
villapx Jan 21 '16 at 17:19 2016-01-21 17:19
source share