Add int conversions to bitset (#29246)

* Better int conversion

* add test
diff --git a/src/core/lib/compression/compression_internal.cc b/src/core/lib/compression/compression_internal.cc
index 01dd6c7..df7646d 100644
--- a/src/core/lib/compression/compression_internal.cc
+++ b/src/core/lib/compression/compression_internal.cc
@@ -194,13 +194,7 @@
 }
 
 uint32_t CompressionAlgorithmSet::ToLegacyBitmask() const {
-  uint32_t x = 0;
-  for (size_t i = 0; i < GRPC_COMPRESS_ALGORITHMS_COUNT; i++) {
-    if (set_.is_set(i)) {
-      x |= (1u << i);
-    }
-  }
-  return x;
+  return set_.ToInt<uint32_t>();
 }
 
 absl::optional<grpc_compression_algorithm>
diff --git a/src/core/lib/gprpp/bitset.h b/src/core/lib/gprpp/bitset.h
index dded433..f88e846 100644
--- a/src/core/lib/gprpp/bitset.h
+++ b/src/core/lib/gprpp/bitset.h
@@ -153,6 +153,18 @@
     return true;
   }
 
+  template <typename Int>
+  typename std::enable_if<std::is_unsigned<Int>::value &&
+                              (sizeof(Int) * 8 >= kTotalBits),
+                          Int>::type
+  ToInt() const {
+    Int result = 0;
+    for (size_t i = 0; i < kTotalBits; i++) {
+      if (is_set(i)) result |= (Int(1) << i);
+    }
+    return result;
+  }
+
  private:
   // Given a bit index, return which unit it's stored in.
   static constexpr size_t unit_for(size_t bit) { return bit / kUnitBits; }
diff --git a/test/core/gprpp/bitset_test.cc b/test/core/gprpp/bitset_test.cc
index dd6204e..3e463ed 100644
--- a/test/core/gprpp/bitset_test.cc
+++ b/test/core/gprpp/bitset_test.cc
@@ -90,6 +90,24 @@
   }
 }
 
+TEST(ToIntTest, ToInt) {
+  auto make_bitset = [](bool b0, bool b1, bool b2) {
+    BitSet<3> b;
+    b.set(0, b0);
+    b.set(1, b1);
+    b.set(2, b2);
+    return b;
+  };
+  EXPECT_EQ(make_bitset(false, false, false).ToInt<uint32_t>(), 0);
+  EXPECT_EQ(make_bitset(true, false, false).ToInt<uint32_t>(), 1);
+  EXPECT_EQ(make_bitset(false, true, false).ToInt<uint32_t>(), 2);
+  EXPECT_EQ(make_bitset(true, true, false).ToInt<uint32_t>(), 3);
+  EXPECT_EQ(make_bitset(false, false, true).ToInt<uint32_t>(), 4);
+  EXPECT_EQ(make_bitset(true, false, true).ToInt<uint32_t>(), 5);
+  EXPECT_EQ(make_bitset(false, true, true).ToInt<uint32_t>(), 6);
+  EXPECT_EQ(make_bitset(true, true, true).ToInt<uint32_t>(), 7);
+}
+
 TEST(EmptyBitSet, Empty) {
   BitSet<0> b;
   EXPECT_TRUE(b.all());