fork download
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. int countLeadingSignBits(int32_t data) {
  5. if (data == 0) {
  6. // Special case for 0, which has no sign bit.
  7. return 31;
  8. }
  9.  
  10. // Determine the value of the most significant bit (MSB)
  11. int32_t msbValue = data < 0 ? 1 : 0;
  12.  
  13. // Initialize count. Start with -1 since we are looking for MSB-1.
  14. int count = -1;
  15.  
  16. // Check each bit, starting from the MSB-1 position
  17. for (int i = 31; i >= 0; --i) {
  18. // Check if the current bit matches the MSB value.
  19. if (((data >> i) & 1) == msbValue) {
  20. count++;
  21. } else {
  22. break;
  23. }
  24. }
  25.  
  26. return count;
  27. }
  28.  
  29. int main() {
  30. int32_t data = 0b11001101; // Replace with your data
  31. int leadingSignBits = countLeadingSignBits(data);
  32.  
  33. // Output the result
  34. printf("Number of leading sign bits minus one: %d\n", leadingSignBits);
  35.  
  36. // If you want to store the result back in data, do so here
  37. data = leadingSignBits;
  38.  
  39. // Output the modified data
  40. printf("Data is now: %d\n", data);
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Number of leading sign bits minus one: 23
Data is now: 23