linux - C write() function sending 2 bytes hexadecimal -
i'm working tcp sockets. i'm sending data open socket using write function.
write(socket_fd, "test", 4);
that works. when way.
#include <stdio.h> #include <stdlib.h> typedef unsigned char byte; typedef struct lanc { byte start; byte end; } lcode; int main(int argc, char *argv[]){ lcode command; command.start = 0x28; command.end = 0x06; short value = (command.start << 8) | command.end; write(socket_fd, value, sizeof(value); return 0; } when check size of value 2 bytes correct since combined 0x28 , 0x06. doing printf.
printf("%x\n", value); output is: 2806 correct. printf("%d\n", sizeof(value); output is: 2 bytes correct. i'm getting error when i'm trying write hexadecimal open socket using write. doing wrong?
you're committing 2 disgusting errors in 1 line (how compile?). you're passing integer (value) write() expects pointer (that won't compile, you're trying deceive code). secondly, you're doing that's endian-dependant, is, on different processors you'll different results depending on whether high-byte of "value" comes first or second in memory.
solution:
unsigned char value[2] = {command.start, command.end}; write(socket_fd, value, sizeof(value));
Comments
Post a Comment