Skip to content

[SPARK-55559][SQL] Fix BitCount to respect input integer type bit width#54631

Open
xiaoxuandev wants to merge 1 commit intoapache:masterfrom
xiaoxuandev:fix-bit-count
Open

[SPARK-55559][SQL] Fix BitCount to respect input integer type bit width#54631
xiaoxuandev wants to merge 1 commit intoapache:masterfrom
xiaoxuandev:fix-bit-count

Conversation

@xiaoxuandev
Copy link

What changes were proposed in this pull request?

Fix BitwiseCount (bit_count) to correctly count set bits for negative values of Byte, Short, and Int types by using java.lang.Byte.toUnsignedInt() / Short.toUnsignedInt() and Integer.bitCount() instead of Long.bitCount() with hardcoded bitmasks. Both the interpreted (nullSafeEval) and codegen (doGenCode) paths are fixed.

Why are the changes needed?

bit_count(CAST(-1 AS TINYINT)) incorrectly returned 64 instead of 8 because java.lang.Long.bitCount() sign-extends smaller integer types to 64-bit before counting. For example, the byte value 0xFF was sign-extended to 0xFFFFFFFFFFFFFFFF, resulting in 64 bits instead of 8.

Does this PR introduce any user-facing change?

Yes. bit_count now returns correct results for negative Byte, Short, and Int values.

How was this patch tested?

Added new test case in BitwiseExpressionsSuite covering negative values for all integer types, including boundary values and consistency checks between interpreted and codegen paths.

Was this patch authored or co-authored using generative AI tooling?

No.

### What changes were proposed in this pull request?

Fix BitwiseCount (bit_count) to correctly count set bits for negative values of Byte, Short, and Int types by using java.lang.Byte.toUnsignedInt() / Short.toUnsignedInt() and Integer.bitCount() instead of Long.bitCount() with hardcoded bitmasks. Both the interpreted (nullSafeEval) and codegen (doGenCode) paths are fixed.

### Why are the changes needed?

bit_count(CAST(-1 AS TINYINT)) incorrectly returned 64 instead of 8 because java.lang.Long.bitCount() sign-extends smaller integer types to 64-bit before counting. For example, the byte value 0xFF was sign-extended to 0xFFFFFFFFFFFFFFFF, resulting in 64 bits instead of 8.

### Does this PR introduce _any_ user-facing change?

Yes. bit_count now returns correct results for negative Byte, Short, and Int values.

### How was this patch tested?

Added new test case in BitwiseExpressionsSuite covering negative values for all integer types, including boundary values and consistency checks between interpreted and codegen paths.

### Was this patch authored or co-authored using generative AI tooling?

No.
@yaooqinn
Copy link
Member

yaooqinn commented Mar 6, 2026

FYI, #52574

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants