How should I by using these bytes(spaces in between each bytes?) and What type of variable would nf
need to be in this context?
if(nf == 0xff 0xd8 0xff 0xe0 || nf == 0xff 0xd8 0xff 0xe1)
CS50 Stack Exchange is a question and answer site for students of Harvard University's CS50. It only takes a minute to sign up.
Sign up to join this communityHow should I by using these bytes(spaces in between each bytes?) and What type of variable would nf
need to be in this context?
if(nf == 0xff 0xd8 0xff 0xe0 || nf == 0xff 0xd8 0xff 0xe1)
That is not technically correct syntax.
There are least two ways that this could be interpreted into working code, depending on the variable type of nf
, which can either be a byte or some other larger value type.
A common scenario is if nf
refers to bytes, for example if nf
is a char
array or pointer, then the if
statement needs a comparison for each byte, e.g:
if ((nf[0] == 0xff && nf[1] == 0xd8 && nf[2] == 0xff && nf[3] == 0xe0)
|| (nf[0] == 0xff && nf[1] == 0xd8 && nf[2] == 0xff && nf[3] == 0xe1))
Another possibility is if nf
refers to a larger data type. In this case you would be accessing 4 bytes, or 32 bits. You might define nf
as a uint32_t
, then compare the entire value in one go.
if (nf == 0xffd8ffe0 || nf == 0xffd8ffe1)
Here the hexadecimal values are all concatenated into one long number, without the need for 0x
for each byte.
Note that while the second solution is shorter to write, and may work in many cases, it is not semantically equivalent to the first solution and care needs to be taken when porting the code to different platforms.
ffd8ffe0
then the compiler would think you were writing the name of a variable. Prefixing the number with 0x
tells the compiler that the following digits are hexadecimal. Once the compiler knows that it interprets all the digits as hex until it reaches a space, bracket, newline, semi-colon, or other delimiter. It is not necessary, nor valid, to repeat 0x
within the hex number.
Aug 10, 2014 at 8:56
The values 0xff, 0xd8, 0xe0 and 0xe1 are int
values that are written in hexadecimal notation.
Since this is for pset5 and, as the pset specification page states, a block is 512 bytes long, we can conclude that none of these values will exceed 0xff(hex) or 255(dec) since each value will be of size 1 byte (8 bits).
As a result, we can use uint8_t
(aka BYTE
) which is an unsigned int
of size 1 byte, declared in stdint.h and defined as BYTE
in bmp.h as a data type for the variable nf
in your example.
If you don't want to include bmp.h, feel free to define that type by putting this statement atop your program in order to use the type name BYTE
instead of uint8_t
interchangeably
typedef uint8_t BYTE;