I have another late night brain-dead question. It’s probably simple to do but you know how it is after 8 hours+ of programming then reaching then end of a deadline. 🙂
Here is my question..
I have a boolean array of length 10 which is logically divided into seperate pieces to hold 4 different integer bit arrays (as booleans). Here is the target array:
bool[] myArray = new bool[10];
And here are the 4 integers I would like to insert:
int value1 = 3; // 2 bits, myArray[0-1], 11
int value2 = 12; // 4 bits, myArray[2-5], 1100
int value3 = 2; // 2 bits, myArray[6-7], 10
int value4 = 1; // 2 bits, myArray[8-9], 01
myArray should end up looking like the following (note that the first element is position 0):
{(T,T),(T,T,F,F),(T,F),(F,T)}
Then ultimately what I want to do is convert myArray to an int value:
0x1111001001 = 969
Perhaps there is an even better way of doing this without having to use booleans? So let me rephrase my question in a more general sense:
How do I concatenate N int values into a target int?
Thanks!
Normally, the common way to combine bits from several numbers into one is this (using your values and bitlengths as examples):
However, the number you printed at the end of your question has the numbers back to front. If that’s what you wanted, it’d be:
Of course this assumes that the code knows the desired bitlength of each value. If you don’t know the bitlength at compile-time, then you have to keep track of it at runtime, otherwise a single int like
1won’t tell your code how many bits to use from it.