Converting an int into a 4 byte char array (C)

后端 未结 10 2180
北荒
北荒 2020-11-27 10:07

Hey, I\'m looking to convert a int that is inputed by the user into 4 bytes, that I am assigning to a character array. How can this be done?

Example:

Convert

10条回答
  •  余生分开走
    2020-11-27 10:26

    An int is equivalent to uint32_t and char to uint8_t.

    I'll show how I resolved client-server communication, sending the actual time (4 bytes, formatted in Unix epoch) in a 1-bit array, and then re-built it in the other side. (Note: the protocol was to send 1024 bytes)

    • Client side

      uint8_t message[1024];
      uint32_t t = time(NULL);
      
      uint8_t watch[4] = { t & 255, (t >> 8) & 255, (t >> 16) & 255, (t >> 
      24) & 255 };
      
      message[0] = watch[0];
      message[1] = watch[1];
      message[2] = watch[2];
      message[3] = watch[3];
      send(socket, message, 1024, 0);
      
    • Server side

      uint8_t res[1024];
      uint32_t date;
      
      recv(socket, res, 1024, 0);
      
      date = res[0] + (res[1] << 8) + (res[2] << 16) + (res[3] << 24);
      
      printf("Received message from client %d sent at %d\n", socket, date);
      

    Hope it helps.

提交回复
热议问题