The Fonz
The Fonz

Reputation: 207

Convert some bytes from a unsigned char to int

I want to convert some bytes to an int. This is my code so far:

unsigned char *bytePtr = (unsigned char *)[aNSDataFrame];

I want to take 4 bytes from this unsigned char: myFrame[10], myFrame[11], myFrame[12] and myFrame[13] and convert them to an integer.

Upvotes: 0

Views: 1039

Answers (3)

LearningC
LearningC

Reputation: 3162

you can do,

int a;
a=myframe[10];
a=a<<8;
a=a|myframe[11];
a=a<<8;
a=a|myframe[12];
a=a<<8;
a=a|myframe[13];

this will create integer containing those bytes

Upvotes: 1

Cy-4AH
Cy-4AH

Reputation: 4585

int val = *(const int*)&myFrame[10];

Upvotes: 1

Yash Patel
Yash Patel

Reputation: 64

int bytesToInt(unsigned char* b, unsigned length)
{

    int val = 0;

    int j = 0;

    for (int i = length-1; i >= 0; --i)
    {
        val += (b[i] & 0xFF) << (8*j);
        ++j;
    }
    return val;
}

Upvotes: 0

Related Questions