John Traynor
John Traynor

Reputation: 13

C bit manipulation char array

I have a pointer to an unsigned char array, e.g. unsigned char *uc_array. If I shift the content that the address points to right by 8 bits will they be in uc_array + 1?

Upvotes: 1

Views: 1243

Answers (5)

porter
porter

Reputation: 1

It's depend on how you shift your data. if you do something like this (quint16)(*uc_array) >> 8 then first byte will move to the second. But if just do (*uc_array) >> 8 then, as says the others you will empty your data.

Upvotes: 0

caf
caf

Reputation: 239041

No. Modifications to a value affect only that value, and not adjacent values. This includes the shift operators.

The bits shifted out by a shift operator are "lost".

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507005

Your question only makes sense to me when interpreted such as

memmove(uc_array + 1, uc_array, bytesize_of_array);

I'm assuming you are on 8 bit byte platform, and that by shifting you mean shift the bits when interpreted as a long bit-sequence of consecutive bytes (and there need to be one char after the array to account for the shift). Then indeed the value stored at address uc_array will then be stored at uc_array + 1.

However if you do a loop like this

for(unsigned char *x = uc_array; x != uc_array + byte_count; ++x)
  *x >>= 8;

And assume 8 bit bytes you will just nullify everything there, byte for byte shifting away all bits.

Upvotes: 0

t0mm13b
t0mm13b

Reputation: 34592

No.... if you dereference a pointer *uc_array++ you are incrementing the value of what the pointer is pointing to. However if you do this, uc_array++ you are incrementing the address of the pointer which points to the "next neighbouring value" returned by *uc_array.

Don't forget that pointer arithmetic is dependent on the size of the type of the pointer, for character pointers, it is 1, for ints, its 4 depending on the platform and compiler used...

Upvotes: 0

icecrime
icecrime

Reputation: 76755

Shifting the content will modify its value, not move it in memory.

Upvotes: 3

Related Questions