Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
char numbers[8] = {0,};

number[0] = 1;
number[1] = 0;
number[2] = 1;
number[3] = 1;
number[4] = 0;
number[5] = 0;
number[6] = 1;
number[7] = 1;

I divide this value by 2 part - 1100 and 1101 - those are 0x0C and 0x0D.

I want to move 0xCD to one byte char variable.

char OneByte;

OneByte = 0xCD;

I don't know the exact operation of above data types.

Please help me.

Thank you

What I have tried:

I have wasted 5 more hours, but failed.
Posted
Updated 22-May-16 20:12pm
Comments
[no name] 23-May-16 1:30am    
Where is your code? Where are you stuck? It seems you are just asking for some code.

1 solution

You can do something like this.
C++
#define LENGTH 8  // Use constants instead of numbers

int numbers[LENGTH];

numbers[0] = 1;   // LSB
numbers[1] = 0;
numbers[2] = 1;
numbers[3] = 1;
numbers[4] = 0;
numbers[5] = 0;
numbers[6] = 1;
numbers[7] = 1;   // MSB

unsigned char result = 0;
int i = 0;
int temp = 0;
for (i=0; i<LENGTH; i++)
{
    if (numbers[i] == 1)
    {
        temp = numbers[i] << i;
        result |= (unsigned char)temp;
    }
}
printf("Result: %02X\r\n", result);


Explanation:

The shift operator will move the value of numbers[i] i steps to the left
Then the shifted value is added to the result
A shift is only necessary if the value of numbers[i] is 1.
i = 0 -> temp = 00000001   -> result = 00000001

i = 2 -> temp = 00000100   -> result = 00000101
i = 3 -> temp = 00001000   -> result = 00001101


i = 6 -> temp = 01000000   -> result = 01001101
i = 7 -> temp = 10000000   -> result = 11001101
 
Share this answer
 
v2
Comments
Kornfeld Eliyahu Peter 23-May-16 3:30am    
Maybe temp += 2^i * numbers[i] will do it quicker (or LENGTH-i, depends on the order of bits)
George Jonsson 23-May-16 3:35am    
Haven't tried, but you might be right.

I tried to explain the code as good as possible, so that is why I added the temp variable in the first place.
At first I had
result |= (unsigned char)(numbers[i] << i);
Kornfeld Eliyahu Peter 23-May-16 3:41am    
Don't take me wrong - your code/explanation is all right, I was only thinking that shifting may be complicated to OP at this point of OP's knowledge...So 'quicker' wasn't toward the execution speed of the app, but toward the understanding speed of OP...
George Jonsson 23-May-16 3:46am    
No worries, I'm old but not grumpy (yet). :)
Difficult to say what is easiest to understand. It has been a few years since I was in the same situation myself.
Sergey Alexandrovich Kryukov 23-May-16 9:30am    
5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900