I have an array of 16 integer values where each value is 32 bits each as shown. I can find the maximum of the array as follows.
#include <stdio.h>
#include <conio.h>
// main program
int main(void){
int i, max;
int array[16];
array[0]=0x1;
array[1]=0x6;
array[2]=0x8;
array[3]=0xC;
array[4]=0x7;
array[5]=0x9;
array[6]=0xB;
array[7]=0x0;
array[8]=0x3;
array[9]=0x6;
array[10]=0x7;
array[11]=0x6;
array[12]=0x15;
array[13]=0x1;
array[14]=0x9;
array[15]=0x3;
// calculate max
max=array[0];
for(int i=1;i<16;i++)
{
if(max<array[i])
{
max=array[i];
}
}
printf("The max is %lx ",max);
getch();
return 0;
I want to find the position of the maximum value in the array and the position of the most significant binary 1 in the maximum value. As can be seen, the maximum value is 0x15 at position 13 in the array and the position of most significant binary 1 in the entry is 5th . How can this be accomplished in C?
put this after the printf statement. and define j at the top.
for (j=0; j<16; j++) {
if ((max=max>>1) == 0) break;
}
printf("the max bit is %lx ", j);
this shows the bit position in conventional notation where the 5th bit is bit 4. add a '+1' to display as bit 5.
to display the position where the max occurs:
below the 'max=array[i]' line, add the following line (after defining maxpos with the other variables)
maxpos = i;
and change the printf to
printf("The max is 0x%02x at position 0x%02x ", max, maxpos);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.