❔ Help me fix my byte-bit conversion function
So I'll first explain my problem, then the solution I've implemented and how it appears to be failing.
I am trying to save an object to a byte array where each item is stored as a bit.
So I have a byte array of 38 bytes. This means I have roughly 300 bits. (actually 304 but we won't use half of a byte)
Now let's say I have the input that I want to save item number 3.
In this case, item number 3's bit will obviously be in the first byte and all I need to do is find the value to add to the byte which essentially does the same as flipping one of the bits from 0 to 1.
So if our bit representation of byte 1 is 00000000 and we want to save item number 3, our bit array should end up looking like 00000100
And this ends up meaning we have to add 4 to the byte.
If we need to save item number 10, it'll be in the second byte or byte index 1.
So there's a really neat way of making all of this work.
The quotient on dividing the index of the item to be saved by 8 gives us the byte we want to write to (actually we need to put the quotient into the floor function first)
Then the remainder can actually tell us the position of the bit to write to.
So if the remainder is 0, we add 128 to the value of the byte and if it isn't, we add Math.Pow(2, rem-1)
I am pretty sure my math is correct here, but for some reason, the amounts being written to the bytes and which bytes they're being written to is wrong.
6 Replies
Here is my code:
(in this case I have used the ceiling function so that my byte index is indexed from 1 which is useful for my use case)
any idea why this might be messing up?
any idea why this might be messing up?
what in the world does any of this mean
you use "bit-array" as if that's an actual thing
bruh... 1. I explained it as best I could. I don't think it is that complicated...
BitArray Class (System.Collections)
Manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).
it's probably not complicated, it's just incomprehensible the way you explained it
so like, is it a
byte[38]
? and you use each bit of each byte as a flag?
if i wanted to set one specific bit to 1
, i'd probably just do it like this?
oh, actually i notice you're reading and writing process memory. you might wanna be careful with that around hereLooks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.