Setting One Bit in BINARY(256)

Question

• I have a BINARY(256) field, which is 2048 bits.  I'm trying to set the value of one bit in the field.  How can I do this?

For simplicity, assume we have 16 bits.  EXA:

STRING OF BITS: 1101 ,0101, 0011,  0001     <-- The hex representation is 0xD531
BIT #:                 7654, 3210, FEDC, BA98     <-- The bit numbers are in hex

Let's set Bit 2 to 0.  I'd like the resultant to be 1101,0001,0011,0001

Thank you.

Trecius

Friday, July 24, 2009 6:57 PM

All replies

• Marked as answer by Friday, July 24, 2009 7:54 PM
Friday, July 24, 2009 7:25 PM
• Thank you, Peso.  I just wasn't sure if we could do a quick "set".  However, the only logic I SAW is by writing an IF-statement.

This is just pseudocode I saw in my head.

IF @newValue = 1
bitString = bitString | (All zeros except @Bit)
ELSE
bitString = bitString & (All ones except @Bit)

Trecius

NOTE: I will implement your solution.  Thank you.
• Edited by Friday, July 24, 2009 7:48 PM Changed see to SAW; Added note
Friday, July 24, 2009 7:43 PM
• Ok then, test this

```CREATE FUNCTION dbo.fnSetMyBit
(
@Value BINARY(128),
@Bit SMALLINT,
@BitValue BIT
)
RETURNS BINARY(128)
AS
BEGIN
RETURN	(