Here are declarations of what I am sending to my server:
typedef enum
{
GET = 0,
SET = 1,
UNDEF = 2,
} cmd_t;
struct args
{
cmd_t cmd;
uint8_t value;
uint8_t id;
};
value
is of type uint8_t
and has for example value 42
and id
is also uint8_t
and has value 30
. cmd
is my typedef
and is for example GET
also 0
.
I send this info to server packed like this:
char buff[2];
buff[0] = arguments.cmd;
buff[0] += arguments.id << 2;
buff[1] = arguments.value;
send(sfd, buff, sizeof(buff), 0);
I pack in the first byte on the first 2 bits my cmd
, then shift it 2 bits and pack the id
. Then on the second byte I pack value
. I know that value can't be bigger than 127
so I can leave it on the first 7 bits of my byte. I also know that id can't be greather that 63
.
Then I receive that on my server. When I read second byte of my response also req[1]
I get value 42
, but when I read my first byte also req[0]
however I shift it I can't get 0
or 30
. req is delared as req[2]
. Here is what I tried:
for (size_t i = 0; i < 8; i++)
{
int idCMD = (uint8_t) (req[0]>>i);
printf("idCMD -> %d\n", idCMD);
}
printf("\n");
for (size_t i = 0; i < 8; i++)
{
int idCMD = (uint8_t) (req[0]<<i);
printf("idCMD -> %d\n", idCMD);
}
How do I read my cmd and id?
output:
idCMD -> 121
idCMD -> 60
idCMD -> 30
idCMD -> 15
idCMD -> 7
idCMD -> 3
idCMD -> 1
idCMD -> 0
idCMD -> 121
idCMD -> 242
idCMD -> 228
idCMD -> 200
idCMD -> 144
idCMD -> 32
idCMD -> 64
idCMD -> 128
What I got out of this is that:
printf("value -> %d\n", req[1]);
printf("id -> %d\n", req[0] >> 2);
printf("cmd-> %d\n", req[0] >> 6);
value -> 42
id -> 30
cmd-> 1
I get that cmd is 1 also. How do I make sure that I read 0 and not 1?
but it seems that I am not reading my cmd
right. The output above is when the cmd
is 1. Here is when the cmd
is 0 and value 0:
idCMD -> 120
idCMD -> 60
idCMD -> 30
idCMD -> 15
idCMD -> 7
idCMD -> 3
idCMD -> 1
idCMD -> 0
idCMD -> 120
idCMD -> 240
idCMD -> 224
idCMD -> 192
idCMD -> 128
idCMD -> 0
idCMD -> 0
idCMD -> 0
value -> 0
id -> 30
cmd-> 1
How do I read cmd correctly and is this correct interpretation?