Reputation: 2466
The code below shown is in visual c++
array<Byte>^ b = gcnew array <Byte> (filesize);
fs->Read(b,0,b->Length);
unsigned char *pb;
pb=(byte*)malloc(b->Length); //pb is unmanaged here.
for(int i=0;i<b->Length;i++)
{
*(pb+i)=InverseByte(b+i);
}
I want to call the function below to reverse each byte. How can I do this? I want to do inverse of each byte of managed array b, and put it in the unmanaged array b.
unsigned char InverseByte(unsigned char* PbByte)
{
//something;
}
Upvotes: 1
Views: 455
Reputation: 3709
From the comments it's clear you are reversing the bytes (i.e. reordering them front-to-back) rather than inverting (i.e. subtracting a variable from its maximum value) or negating (i.e. flipping 1's and 0's), so should name the function accordingly.
Here's a neat little snippet from Seander's bithacks:
unsigned int v; // input bits to be reversed
unsigned int r = v; // r will be reversed bits of v; first get LSB of v
int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end
for (v >>= 1; v; v >>= 1)
{
r <<= 1;
r |= v & 1;
s--;
}
r <<= s; // shift when v's highest bits are zero
return r;
If you combine Hans Passant's answer with this, you should have all the pieces to put together your function.
Upvotes: 1
Reputation: 46629
unsigned char InverseByte(unsigned char c)
{
return (c>>7)|((c&64)>>5)|((c&32)>>3)|((c&16)>>1)|((c&8)<<1)|((c&4)<<3)|((c&2)<<5)|((c&1)<<7);
}
Upvotes: 1
Reputation: 613612
You mean bitwise negation I presume.
unsigned char InverseByte(unsigned char c)
{
return ~c;
}
Note that I changed the parameter to pass by value rather than passing a pointer to the value.
I also fail to see why you are using pointer arithmetic instead of indexing. That just makes your code harder to read. The loop should be written like this:
for(int i=0;i<b->Length;i++)
{
pb[i] = InverseByte(b[i]);
}
Upvotes: 2
Reputation: 942548
Fix the declaration of InverseByte:
unsigned char InverseByte(unsigned char value)
So you can then use it like this:
for (int i=0; i < b->Length; i++)
{
pb[i] = InverseByte(b[i]);
}
Upvotes: 3