4

Say you have two binary values

001011 
001111

How can you get the number of different bits in MySQL? I tried

SELECT BIT_COUNT(BINARY  001011 ^ BINARY 001111)

This returns 6, while I need a solution that returns 1 in this example.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Sheqel
  • 43
  • 1
  • 3

3 Answers3

3
SELECT BIT_COUNT( CONV( '001011', 2, 10 ) ^ CONV( '001111', 2, 10 ) )
nobody
  • 10,599
  • 4
  • 26
  • 43
  • How about for large binary strings? It seems to cap out at 2^16 or thereabout. – Sheqel Aug 18 '11 at 18:11
  • I'm using MySql 5.1 and it doesn't seem to have a cap `SELECT CONV( '11111111111111111111111111111111', 2, 10 )` returns `4294967295` as expected. – nobody Aug 18 '11 at 18:17
  • I'm trying this example: SELECT BIT_COUNT( CONV( 1111111110011111000001000000111000000110100011001111011101010100, 2, 10 ) ^ CONV( 1111111110011111000001000001111000000110100011010000000110010000, 2, 10 ) ) (there are a couple of bits different in the middle somewhere, but it returns 0) thanks again. – Sheqel Aug 18 '11 at 18:30
  • @Sheqel After doing some tests I figured out there is a 63bit limit, I suppose it's related to the sign bit. BTW put the first argument between quotes or it will be interpreted as a base10 number. – nobody Aug 18 '11 at 19:03
3
SELECT BIT_COUNT(b'001011' ^ b'001111');
coyotebush
  • 643
  • 6
  • 10
0

It's converting the numbers 1011 and 1111 (base 10) to binary and doing the comparison. If you did:

SELECT BIT_COUNT(11 ^ 15)

It'd work.

James
  • 20,957
  • 5
  • 26
  • 41