0

How to convert an short to unsigned char *buf in C ?

I read my data

short read_raw_data(int addr) {
    short high_byte, low_byte, value;
    high_byte = wiringPiI2CReadReg8(fd, addr);
    low_byte = wiringPiI2CReadReg8(fd, addr + 1);
    value = (high_byte << 8) | low_byte;
    return value;
}

and want to send it with

lws_write(struct lws *wsi, unsigned char *buf, size_t len, enum lws_write_protocol protocol);

like

m = lws_write(wsi, myShortConvertedToUnsignedChar + LWS_PRE, 32, LWS_WRITE_TEXT);

How to do this ?

hannes ach
  • 16,247
  • 7
  • 61
  • 84
  • 5
    Step one is to drop all the default integer types and start using stdint.h. You should _only_ be using uint8_t, uint16_t and perhaps uint32_t in this snippet, because you have multiple issues with signed bitwise arithmetic and implicit type promotion. – Lundin Nov 02 '21 at 07:31

1 Answers1

2

Just use a cast to convert a pointer to value to unsigned char:

short value = ...;
lws_write(wsi, (unsigned char*)&value, sizeof value, LWS_WRITE_TEXT);
tstanisl
  • 13,520
  • 2
  • 25
  • 40
  • 1
    It is also necessary to be aware of the byte order. In this case, the sent bytes will depend on whether the system is little-endian or big-endian. – nielsen Nov 02 '21 at 09:40
  • @nielsen Please can you explain it in an example ? – hannes ach Nov 03 '21 at 06:03
  • @hannesach See e.g. the answer here: https://stackoverflow.com/questions/22030657/little-endian-vs-big-endian – nielsen Nov 03 '21 at 07:03
  • @tstanisl Do you have a hint here too ? https://stackoverflow.com/questions/69822300/how-to-convert-serveral-floats-to-unsigned-char-buf-in-c – hannes ach Nov 03 '21 at 13:15
  • 1
    @hannesach, try ```char buf[1024]; sprintf(buf, "%.3f %.3f %.3f %.3f %.3f %.3f\n", Gx, Gy, Gz, Ax, Ay, Az); lws_write(wsi, (unsigned char*)buf, strlen(buf), LWS_WRITE_TEXT);``` – tstanisl Nov 03 '21 at 14:57