I have a program that reads a binary file of 20 bytes, modifies the data and then write on another binary file. I am trying to check if the source port is bigger than 32767 or(0x7FFF). If it is bigger then I must zero out the most significant two bits of it. I am only allowed to use bitwise operators. Anybody has any idea how could I do it? Thanks.
Data: 32 27 A9 49 03 8C BD 89 01 87 9B 8D 50 13 00 00 FF FF 00 00
Source port: 32 27 (16 bits)
void modify(const unsigned char oldData [], unsigned char newData []){
/*Accessing the souce port oldData[0] and oldData[1].*/
}
Just pick out the port value from the data. This depends on endianness. little or big.
You will need to know how your data is organized - if the 32 is the high or low part.
Assuming your data is little-endian, you can read it like this:
#include <endian.h>
void modify()
{
uint16_t port = le16toh( *((uint16_t*)oldData) );
if(port>32767)
{/*whatever*/}
For the particular case of checking against >=32768 , which is >=0x8000, can test the high-bit as already commented:
if(oldData[1]&0x80) // [1] is highbyte if using little-endian data.
{/*whatever*/}