简体   繁体   中英

C : convert to integer using bits

C : convert to integer using bits

I need to get integer value from bit arrays of 0, 1.

I want to pass integer arrays and get the decimal number using bit operator.

The following is what I tried but does not work when I tried to pass int arrays, it works with . Is there any way that I can pass int arrays and convert it to decimal number? I want to use bit operator.

 int toInt(int* bin_arr) {

  int val = 0;
  while (*bin_arr)
   val = (val << 1) | (*bin_arr++ == '1');
  return val;
 }

Thanks in advance.

Your loop condition assumes that the array is 0-terminated, which is valid for strings, but not integer arrays. One way to fix this would be to pass a length parameter along with the int pointer, so you know when to stop iterating.

Also, in this expression:

(*bin_arr++ == '1')

you should remove the single quotes, if you're passing integers rather than characters.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM