M
mark
Hello-
i am trying to make the function addbitwise more efficient. the code
below takes an array of binary numbers (of size 5) and performs
bitwise addition. it looks ugly and it is not elegant but it appears
to work. using time, i measured it takes .041s to execute, which i
admit isnt much. but, the problem is that this procedure will be
called many, many times in my project (probably at least a few
thousand times, if not more) so thus, efficiency very is important.
any suggestions (and explanations)? thanks...!
mark.
int main()
{
int arr1[5];
int arr2[5];
arr1[0] = 0;
arr1[1] = 1;
arr1[2] = 0;
arr1[3] = 0;
arr1[4] = 0;
arr2[0] = 1;
arr2[1] = 0;
arr2[2] = 1;
arr2[3] = 1;
arr2[4] = 0;
addbitwise(arr1, arr2);
exit(1);
}
int addbitwise(int x[], int y[])
{
int result[5];
int i, carry = 0;
for (i=4; i>=0; i--)
{
result = x ^ y; /* result of the bitwise
add */
if (x & y) /* a carry has occured */
{
carry = 1;
if (i != 0) /* prevents final iteration */
{ /* from peeking out of bounds */
if (x[i-1] == 0)
{
x[i-1] = 1; /* replace the next 0 bit with the carry'd 1 */
carry = 0;
}
else if (y[i-1] == 0) /* peek at the next array bit */
{
y[i-1] = 1;
carry = 0;
}
}
}
}
return(carry);
}
_____________________
Mark Fonnemann
Boston College
B.A., Computer Science 2000
M.A., Mathematics 2002
_____________________
i am trying to make the function addbitwise more efficient. the code
below takes an array of binary numbers (of size 5) and performs
bitwise addition. it looks ugly and it is not elegant but it appears
to work. using time, i measured it takes .041s to execute, which i
admit isnt much. but, the problem is that this procedure will be
called many, many times in my project (probably at least a few
thousand times, if not more) so thus, efficiency very is important.
any suggestions (and explanations)? thanks...!
mark.
int main()
{
int arr1[5];
int arr2[5];
arr1[0] = 0;
arr1[1] = 1;
arr1[2] = 0;
arr1[3] = 0;
arr1[4] = 0;
arr2[0] = 1;
arr2[1] = 0;
arr2[2] = 1;
arr2[3] = 1;
arr2[4] = 0;
addbitwise(arr1, arr2);
exit(1);
}
int addbitwise(int x[], int y[])
{
int result[5];
int i, carry = 0;
for (i=4; i>=0; i--)
{
result = x ^ y; /* result of the bitwise
add */
if (x & y) /* a carry has occured */
{
carry = 1;
if (i != 0) /* prevents final iteration */
{ /* from peeking out of bounds */
if (x[i-1] == 0)
{
x[i-1] = 1; /* replace the next 0 bit with the carry'd 1 */
carry = 0;
}
else if (y[i-1] == 0) /* peek at the next array bit */
{
y[i-1] = 1;
carry = 0;
}
}
}
}
return(carry);
}
_____________________
Mark Fonnemann
Boston College
B.A., Computer Science 2000
M.A., Mathematics 2002
_____________________