Right,

I am attempting to parse a DNS reply, an IPv6 one specifically. The ip is split up into its segments with two bytes used to represent each segment. I have a pointer to the data, currently an unsigned char *c. I have tried simply setting an int to equal the value at the pointer but only the first byte is taken into consideration. I have experimented with short ints but can't get a variable to equal the value of the first two bytes :(

To clarify. I have two bytes something like 00000001 00000010. I have a pointer pointing to the first byte. I want to make an int that would equal 258 in this case, but I can only make them equal 1 or 2.

Any help would be greatly appriciated.

E1

That's actually correct. A char * points to chars, not ints or anything else. So saying: int i = *s; causes the computer to go get the (eight-bit) char at *s, then assign the value to the int i.

If you want to get bigger numbers, you'll need to read two characters and stick them together:

i = (s[ 0 ] << 8) +s[ 1 ];

There are other ways to do this but the way I've described is safest. (There are a whole host of technical reasons why, including the width of a char, the endianness of your machine, the size of an int, etc.)

Hope this helps.

Ah, ok. I wasn't aware that when you sent an int to the value pointed to by a char pointer it actually took into account the fact that it was a char pointer rather than any other pointer. I tried your code and it works fine. I assume the << 8 is bitshifting the first byte after it has been placed into the int, hence the brackets?

If I wanted to write a 4 byte int to two bytes would I be able to increment the int pointer by 2 and then copy the bytes as they are?

Thanks again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.