0

I need to send a signed short integer but the sendto function requires me to give a char buffer.

The buffer: char SendBuffer[1024];

I was thinking of making the integer into a string and storing it like that but I am wondering if there is a better way to do it.

  • Does this answer your question? [Converting an int into a 4 byte char array (C)](https://stackoverflow.com/questions/3784263/converting-an-int-into-a-4-byte-char-array-c) – KagurazakaKotori Nov 21 '20 at 12:50

2 Answers2

1

As you did not provide any code you have two options.

I assume that function sendto was declared as:

int sendto(const void *buff, size_t len);

You have two options:

  1. Do not copy or convert anything:
short x;

/* some code */

sendto(&x, sizeof(x));

You may copy the context of the x to char buffer by using memcpy

memcpy(SendBuff, &x sizeof(x));
sendto(SendBuff, sizeof(x));
0___________
  • 60,014
  • 4
  • 34
  • 74
1

Actually, this is the declaration of sendto():

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
                  const struct sockaddr *dest_addr, socklen_t addrlen);

The buffer is of type void* so you can pass it a pointer to any type of variable.

In your case:

short your_variable;
short *buffer = &your_variable;

sendto(sockfd, buffer, sizeof(your_variable), flags, ...);
Fabio
  • 376
  • 6
  • 19
  • 2
    why not simple `sendto(sockfd, &your_variable, sizeof(your_variable), flags, ...);`. What is the purpose of the `buffer`? – 0___________ Nov 21 '20 at 13:42
  • 1
    @P__JsupportswomeninPoland it's the same, I just wanted to make it more explicit – Fabio Nov 21 '20 at 13:51