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, 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)
bitString = bitString & (All ones except @Bit)
NOTE: I will implement your solution. Thank you.
- Edited by Trecius Friday, July 24, 2009 7:48 PM Changed see to SAW; Added note
Ok then, test this
CREATE FUNCTION dbo.fnSetMyBit ( @Value BINARY(128), @Bit SMALLINT, @BitValue BIT ) RETURNS BINARY(128) AS BEGIN RETURN ( SELECT theLead + CASE @BitValue WHEN 1 THEN CAST(theOctet | POWER(2, @Bit % 8) AS BINARY(1)) ELSE theOctet END + theTrail FROM ( SELECT SUBSTRING(@Value, 1, @Bit / 8) AS theLead, SUBSTRING(@Value, 2 + @Bit / 8, DATALENGTH(@Value)) AS theTrail, CAST(CAST(SUBSTRING(@Value, 1 + @Bit / 8, 1) AS TINYINT) & (255 - POWER(2, @Bit % 8)) AS BINARY(1)) AS theOctet ) AS d ) END