C
C#2y ago
Ertuğrul

❔ Data Parsing

Hello,I'm trying to built a simulation program by using windows forms application and I have a question:I want to parse a byte array bit by bit by using struct method and udp protocol.But I couldn't figure out how I can parse the byte array bit by bit.If someone can help I would appreciate it
11 Replies
mtreit
mtreit2y ago
What does "parse bit by bit" mean in your scenario?
Ertuğrul
ErtuğrulOP2y ago
most of the data I'm gonna parse is 1 bit length so ı need a way to parse byte array but each bit individually so that I can parse all the data I need I don't know If I'm able to tell what I'm trying to say 🙂
mtreit
mtreit2y ago
Typically if you want to work with individual bits you would create a mask containing the bit you want to examine and then use bitwise and (the & operator) to test if that bit is set.
MODiX
MODiX2y ago
mtreit#6470
REPL Result: Success
int mask = 1;
byte val = 100;

for (int i = 0; i < 8; i++)
{
int bit = (val & mask) == 0 ? 0 : 1;
Console.Write(bit);

mask <<= 1;
}
int mask = 1;
byte val = 100;

for (int i = 0; i < 8; i++)
{
int bit = (val & mask) == 0 ? 0 : 1;
Console.Write(bit);

mask <<= 1;
}
Console Output
00100110
00100110
Compile: 521.753ms | Execution: 47.575ms | React with ❌ to remove this embed.
Ertuğrul
ErtuğrulOP2y ago
ok here you compartmentalize the data for specific byte value and within that value all the bits right ?
mtreit
mtreit2y ago
That code just walks the bit pattern from least significant bit to most significant bit (right to left, if you want to think of it that way) and outputs the bit value.
Ertuğrul
ErtuğrulOP2y ago
I understand
mtreit
mtreit2y ago
The opposite direction:
MODiX
MODiX2y ago
mtreit#6470
REPL Result: Success
int mask = 128;
byte val = 100;

for (int i = 8; i > 0; i--)
{
int bit = (val & mask) == 0 ? 0 : 1;
Console.Write(bit);

mask >>= 1;
}
int mask = 128;
byte val = 100;

for (int i = 8; i > 0; i--)
{
int bit = (val & mask) == 0 ? 0 : 1;
Console.Write(bit);

mask >>= 1;
}
Console Output
01100100
01100100
Compile: 572.280ms | Execution: 46.347ms | React with ❌ to remove this embed.
Omnissiah
Omnissiah2y ago
there's the BitArray class if you want to read the bits one by one
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server