Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
ynohtna
Feb 16, 2007

backwoods compatible
Illegal Hen

Rocko Bonaparte posted:

I'm about to walk into a forest of rakes on the ground in some code using Boost asio.

Adbot
ADBOT LOVES YOU

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
Even better, it has threads. So it's threads with coroutines in them. Who started them? To what purpose? It is a mystery!

Zopotantor
Feb 24, 2013

...und ist er drin dann lassen wir ihn niemals wieder raus...

Rocko Bonaparte posted:

Even better, it has threads. So it's threads with coroutines in them. Who started them? To what purpose? It is a mystery!

Just a little while and you can shoehorn std::execution in there too.

NGL, std:: execution looks pretty neat.

Ihmemies
Oct 6, 2012

I just wanted to drop by and state that bit operators in C are pure hell. Like I have to swap signed char pointer's bits around. 01001001 to 10010010 etc.

I can swap values in an array, but understanding how to do that poo poo with bit operations is beyond me.

*ptr |= (1 << 1); *ptr |= 1; first_bit = (*ptr & 1); etc... maybe I'll understand that some day. Otherwise I'm just skipping this and hope I never have to manually adjust bit values again. I don't even want to know why anyone would ever want to do anything like this. I wish I could move on from C and C++ to something reasonable like rust or C#. These legacy languages are so goddamn sweaty.

leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.

Ihmemies posted:

I just wanted to drop by and state that bit operators in C are pure hell. Like I have to swap signed char pointer's bits around. 01001001 to 10010010 etc.

I can swap values in an array, but understanding how to do that poo poo with bit operations is beyond me.

*ptr |= (1 << 1); *ptr |= 1; first_bit = (*ptr & 1); etc... maybe I'll understand that some day. Otherwise I'm just skipping this and hope I never have to manually adjust bit values again. I don't even want to know why anyone would ever want to do anything like this. I wish I could move on from C and C++ to something reasonable like rust or C#. These legacy languages are so goddamn sweaty.

Cast to unsigned. What's the problem?

giogadi
Oct 27, 2009

Ihmemies posted:

I just wanted to drop by and state that bit operators in C are pure hell. Like I have to swap signed char pointer's bits around. 01001001 to 10010010 etc.

I can swap values in an array, but understanding how to do that poo poo with bit operations is beyond me.

*ptr |= (1 << 1); *ptr |= 1; first_bit = (*ptr & 1); etc... maybe I'll understand that some day. Otherwise I'm just skipping this and hope I never have to manually adjust bit values again. I don't even want to know why anyone would ever want to do anything like this. I wish I could move on from C and C++ to something reasonable like rust or C#. These legacy languages are so goddamn sweaty.

Is this for a class?

It’s sweaty because you’re doing sweaty stuff. If you wanted to work with bits in any other language it would also be sweaty

Ihmemies
Oct 6, 2012

giogadi posted:

Is this for a class?

It’s sweaty because you’re doing sweaty stuff. If you wanted to work with bits in any other language it would also be sweaty

Yes. Thanks. Why would anyone want to work with bits though...

leper khan posted:

Cast to unsigned. What's the problem?

Because I do not actually understand a word I'm reading, either from the course materials, ansi C book or stackoverflow or any other source. The material just flows off my brains like water from duck's back.

I've been hours at this thing. I finally asked chatGPT because I still have 12 more exercises to do this week.

C code:
void kaannaScharBitit(signed char *ptr)
{
    char x = *ptr;
    char result = 0;
    int i = 0;

    for (; i < CHAR_BIT; ++i) {
        result |= ((x >> i) & 1) << (CHAR_BIT-1 - i);
    }

    *ptr = result;
}
It even tries to explain to me what is happening. My brains refuse to understand.

"This code first stores the value pointed to by ptr in a local variable x. The loop then iterates over each bit in x, from the least significant bit to the most significant bit. For each bit, the result variable is updated by first isolating the bit with the & operator and the 1 value, and then shifting it to the appropriate position with the << operator. Finally, the result is stored back into the memory location pointed to by ptr."

It seems to work since this produces results combined with the above function:

C code:
long int lx = 2015;
signed char cx = lx;

tulosta_schar_bitit(cx);
kaannaScharBitit(&cx);
tulosta_schar_bitit(cx);

void tulosta_schar_bitit(signed char x)
{
    int i;
    int j = 0;
    char str[CHAR_BIT];
    printf("%d\n", x);

    /* convert char to a binary string, char by char */
    for (i = CHAR_BIT-1; i >= 0; i--) {
        if ((x >> i) & 1) {
            str[j] = '1';
        } else {
            str[j] = '0'; }
        j++;
    }
    /* print the string char by char */
    for (i = 0; i < CHAR_BIT; i++) {
        putchar(str[i]);
    }
    putchar('\n');
}
code:
-33
11011111
-5
11111011

Zopotantor
Feb 24, 2013

...und ist er drin dann lassen wir ihn niemals wieder raus...

Ihmemies posted:

I just wanted to drop by and state that bit operators in C are pure hell. Like I have to swap signed char pointer's bits around. 01001001 to 10010010 etc.

I can swap values in an array, but understanding how to do that poo poo with bit operations is beyond me.

*ptr |= (1 << 1); *ptr |= 1; first_bit = (*ptr & 1); etc... maybe I'll understand that some day. Otherwise I'm just skipping this and hope I never have to manually adjust bit values again. I don't even want to know why anyone would ever want to do anything like this. I wish I could move on from C and C++ to something reasonable like rust or C#. These legacy languages are so goddamn sweaty.

https://graphics.stanford.edu/~seander/bithacks.html

Ihmemies
Oct 6, 2012

This course would probably be easier, if it existed in some real form. Now it is a self-study course consisting of ~80 exercises, a 155-page PDF and an exam. No lectures, no assistance or anything really. Just a bunch of old slides from year X and a bunch of excericses you have to do.

Volguus
Mar 3, 2009
Would this be easier to understand? https://en.wikipedia.org/wiki/Bitwise_operation

giogadi
Oct 27, 2009

Ihmemies posted:

Yes. Thanks. Why would anyone want to work with bits though...

Now this is an excellent question. It’s your terrible class’s fault for failing to motivate this stuff. Of course you hate it if you don’t even know why you’re mucking around in it.

There are a million uses for bitwise operations. One of the fun uses is that sometimes, you can store data in bits way more efficiently than anything else.

For example, if you have a long array of data, where some items are occupied/valid and other items are empty/invalid, you can store the occupied/empty status of each element in a big ol’ bitstring. This is more efficient than storing a bool for each item because a bool is usually at least 8 bits.

Then you can do clever stuff like iterating over only the occupied items way faster than if you were iterating one-by-one over each item and checking “is this occupied or not?”

This is all fancy stuff to squeeze out performance/space. Probably most fancy bit operations are for this kind of thing. You also need to do bitwise operations when working in embedded systems or communicating with hardware without a fancy high-level api.

Ihmemies
Oct 6, 2012

I will have to study this thing more. Some things are a bit tough while you have four other courses ongoing and every course has a bunch of stuff to learn + all the homework and coding exercises. I wish I had more time or was a faster/better leaner. Thanks for the help :)

Phobeste
Apr 9, 2006

never, like, count out Touchdown Tom, man
I cannot imagine trying to self study stuff like that without motivating examples or an actual teacher honestly. Here are some motivating examples:
- what somebody said (phone can’t see previous posts while typing I forgot who it was) about storing yes/no or present/not present results in less space
- in general, storing values that can be fully represented in lengths other than 8, 32, or 64 bits more efficiently. This is valuable for optimization like that poster said but it’s not just high end stuff you’ll never do - some on-the-wire serialization formats use this, or the low level equivalent of IPC in embedded systems, register-model interfaces that look like the next example
- controlling a system where different bits mean different things, which is common in embedded device memory-mapped io (bit N of the byte at 0x8008354 controls pin N of the gpio port)
- walking or accessing a buffer of packed values

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

Ihmemies posted:

I can swap values in an array, but understanding how to do that poo poo with bit operations is beyond me.
The thing is that doing this with an array of 8 values isn't fundamentally different. You're going to want to swap a[0] with a[7], and a[1] with a[6], and so on, but instead of array indices you want "bit zero" swapped with "bit seven", and so forth. Doing this with an array, you'd write something very close to what you've posted below, but of course this looks a lot friendlier because bit-twiddling looks gnarly.

Something I'd recommend for you to do is rather than write result |= ((x >> i) & 1) << (CHAR_BIT-1 - i); all on one line, because you're new to this variation of "looping through a collection of things" (individual bits rather than array elements), break things down into their own loop variables. Such variables might include:

* a bitwise _mask_ that removes all but the ith bit of the input character (so it's 0 if that bit is 0, and some nonzero value if that bit is 1);
* a value of 1 if the ith bit in your input character is set, and 0 otherwise;
* the ith bit of the input character, but placed at bit (8-i)

Once you have the third value, you can use a bitwise-or operation to "slice" it into your output character.

Spatial
Nov 15, 2007

giogadi posted:

Is this for a class?

It’s sweaty because you’re doing sweaty stuff. If you wanted to work with bits in any other language it would also be sweaty
Not Verilog. :v:

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

Dijkstracula posted:

The thing is that doing this with an array of 8 values isn't fundamentally different. You're going to want to swap a[0] with a[7], and a[1] with a[6], and so on, but instead of array indices you want "bit zero" swapped with "bit seven", and so forth. Doing this with an array, you'd write something very close to what you've posted below, but of course this looks a lot friendlier because bit-twiddling looks gnarly.

Something I'd recommend for you to do is rather than write result |= ((x >> i) & 1) << (CHAR_BIT-1 - i); all on one line, because you're new to this variation of "looping through a collection of things" (individual bits rather than array elements), break things down into their own loop variables. Such variables might include:

* a bitwise _mask_ that removes all but the ith bit of the input character (so it's 0 if that bit is 0, and some nonzero value if that bit is 1);
* a value of 1 if the ith bit in your input character is set, and 0 otherwise;
* the ith bit of the input character, but placed at bit (8-i)

Once you have the third value, you can use a bitwise-or operation to "slice" it into your output character.

this is good advice but also you may find it really helpful to make diagrams (even just binary sequences) on paper as you work it out

Zopotantor
Feb 24, 2013

...und ist er drin dann lassen wir ihn niemals wieder raus...

Dijkstracula posted:

The thing is that doing this with an array of 8 values isn't fundamentally different. You're going to want to swap a[0] with a[7], and a[1] with a[6], and so on, but instead of array indices you want "bit zero" swapped with "bit seven", and so forth. Doing this with an array, you'd write something very close to what you've posted below, but of course this looks a lot friendlier because bit-twiddling looks gnarly.

Something I'd recommend for you to do is rather than write result |= ((x >> i) & 1) << (CHAR_BIT-1 - i); all on one line, because you're new to this variation of "looping through a collection of things" (individual bits rather than array elements), break things down into their own loop variables. Such variables might include:

* a bitwise _mask_ that removes all but the ith bit of the input character (so it's 0 if that bit is 0, and some nonzero value if that bit is 1);
* a value of 1 if the ith bit in your input character is set, and 0 otherwise;
* the ith bit of the input character, but placed at bit (8-i)

Once you have the third value, you can use a bitwise-or operation to "slice" it into your output character.

Actually, you might be able to just replicate the array swapping code with a std::bitset<8> and let the sufficiently intelligent compiler derive all the bit twiddling stuff.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
I keep having to reimplement bit vectors despite having access to the STL ones. The STL bitvectors are perfectly fine implementations, but they’re missing a lot of key operations. The only bitset-specific operation on std::vector<bool> is flip, and std::bitset only adds a handful of operations: any, all, &, |, and ^. Both are missing operations like “popcount”, “iterate all of the set bits”, and “find the lowest/highest set bit”, all of which can be done significantly more efficiently on bit vectors than a generic algorithm would reasonably get optimized to.

giogadi
Oct 27, 2009

rjmccall posted:

I keep having to reimplement bit vectors despite having access to the STL ones. The STL bitvectors are perfectly fine implementations, but they’re missing a lot of key operations. The only bitset-specific operation on std::vector<bool> is flip, and std::bitset only adds a handful of operations: any, all, &, |, and ^. Both are missing operations like “popcount”, “iterate all of the set bits”, and “find the lowest/highest set bit”, all of which can be done significantly more efficiently on bit vectors than a generic algorithm would reasonably get optimized to.

100%. Such a missed opportunity to not at least provide an iterator on set bits

Not So Fast
Dec 27, 2007


giogadi posted:

Now this is an excellent question. It’s your terrible class’s fault for failing to motivate this stuff. Of course you hate it if you don’t even know why you’re mucking around in it.

There are a million uses for bitwise operations. One of the fun uses is that sometimes, you can store data in bits way more efficiently than anything else.

For example, if you have a long array of data, where some items are occupied/valid and other items are empty/invalid, you can store the occupied/empty status of each element in a big ol’ bitstring. This is more efficient than storing a bool for each item because a bool is usually at least 8 bits.

Then you can do clever stuff like iterating over only the occupied items way faster than if you were iterating one-by-one over each item and checking “is this occupied or not?”

This is all fancy stuff to squeeze out performance/space. Probably most fancy bit operations are for this kind of thing. You also need to do bitwise operations when working in embedded systems or communicating with hardware without a fancy high-level api.

This is exactly how low bitrate transmission of data works at my workplace, where we are getting up streams of data from tools that communicate by sending up pulses through mud.

Computer viking
May 30, 2011
Now with less breakage.

Most file formats are heavy on the bit ops, too. I've written code to fiddle with OpenType (and the weird Adobe formats in the data blocks inside), torrent files, IPFS and Agilent CEL files, and all of them stuffed more than one thing into a byte, at times. Not just flags, either, but "these five bits give the number of config blocks" or whatever.

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

Zopotantor posted:

Actually, you might be able to just replicate the array swapping code with a std::bitset<8> and let the sufficiently intelligent compiler derive all the bit twiddling stuff.

Given the OP is stucking reading K&R my first thought would be that the C++ STL is probably out of scope for the assignment

but my second thought was "given how incompetent the instructor seems to be, maybe they wouldn't notice if it was used"

nelson
Apr 12, 2009
College Slice
Playing with bits is also something you might encounter with embedded devices as well.

Edit: Oops, that’s already been mentioned. Oh well, repeated for emphasis because embedded devices are fun.

nelson fucked around with this message at 22:30 on Feb 2, 2023

shame on an IGA
Apr 8, 2005

this is fun to play with if you have access to android hardware, when you're looking for more reasons to play with bitwise operators

https://youtu.be/4K9C3OBCDDc

shame on an IGA fucked around with this message at 22:49 on Feb 2, 2023

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Not So Fast posted:

This is exactly how low bitrate transmission of data works at my workplace, where we are getting up streams of data from tools that communicate by sending up pulses through mud.
This is the best thing, and those of us who like bits should all get this job.

Volguus
Mar 3, 2009

roomforthetuna posted:

This is the best thing, and those of us who like bits should all get this job.

With that being said, don't overdo it. The compiler is usually very capable in generating correct and fast code out of your human-readable thing. Don't forget: the compiler is your friend. One with tens of thousands of man-hours sunken into it.

shame on an IGA
Apr 8, 2005

Not So Fast posted:

This is exactly how low bitrate transmission of data works at my workplace, where we are getting up streams of data from tools that communicate by sending up pulses through mud.

that sounds Not So Fast

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Volguus posted:

With that being said, don't overdo it. The compiler is usually very capable in generating correct and fast code out of your human-readable thing. Don't forget: the compiler is your friend. One with tens of thousands of man-hours sunken into it.
For sure. It bears repeating (because I love it) that if you write pretty much any variant of the classic "reverse the order of the bytes in a 4-byte value" code, e.g.
code:
x = (x&255)<<24 + (x&(255<<8))<<8 + (x&(255<<16))>>8 + (x&(255<<24))>>24;
... then when optimized it will compile into a single assembler "bswap" instruction, despite looking like so many operations.

Though I also enjoy that sometimes it's tricky to prove because if you put this operation (or function and function call) somewhere it can be inlined the compiler will be like "gently caress it, I can just assign the pre-swapped value in the first place and do no operations at all!"

C[++] compilers are amazing beasts.

But also, I don't think you really care too much about compiler optimizations when you're parsing mud-pulses.

csammis
Aug 26, 2003

Mental Institution
std::blorp<> standardized when

StumblyWumbly
Sep 12, 2007

Batmanticore!
Does internet of mud have a lot of bugs, still, or are frogs the bigger problem?

Ihmemies
Oct 6, 2012

Zopotantor posted:

Actually, you might be able to just replicate the array swapping code with a std::bitset<8> and let the sufficiently intelligent compiler derive all the bit twiddling stuff.

I don't think this is a supported feature in ANSI C sadly, so I must do this manually. The C standard library doesn't include that much stuff.

Dijkstracula posted:

Given the OP is stucking reading K&R my first thought would be that the C++ STL is probably out of scope for the assignment

but my second thought was "given how incompetent the instructor seems to be, maybe they wouldn't notice if it was used"

The automatic tester compiles the code with -ansi flag :v:

Ihmemies fucked around with this message at 20:28 on Feb 3, 2023

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

Ihmemies posted:

I don't think this is a supported feature in ANSI C
yeah this is a C++ thing :v:

Ihmemies posted:

I don't think this is a supported feature in ANSI C sadly, so I must do this manually. The C standard library doesn't include that much stuff.

The automatic tester compiles the code with -ansi flag :v:
lol so much for that then!

(So many times I've seen intro-to-C classes obsessed with ancient versions of the language spec and I'm never sure why instructors think this makes for a better learning experience)

ultrafilter
Aug 23, 2007

It's okay if you have any questions.


Dijkstracula posted:

(So many times I've seen intro-to-C classes obsessed with ancient versions of the language spec and I'm never sure why instructors think this makes for a better learning experience)

It's what they know.

His Divine Shadow
Aug 7, 2000

I'm not a fascist. I'm a priest. Fascists dress up in black and tell people what to do.

Ihmemies posted:

This course would probably be easier, if it existed in some real form. Now it is a self-study course consisting of ~80 exercises, a 155-page PDF and an exam. No lectures, no assistance or anything really. Just a bunch of old slides from year X and a bunch of excericses you have to do.

I thought the bitwise stuff look neat and interesting from what little I've seen of them so far.

This guy explained the concept well for how you'd use bit fields and it sounds very useful to me.

https://www.youtube.com/watch?v=aMAM5vL7wTs

I went and studied hex to binary tables a little after this, made it easier to follow the video.

His Divine Shadow fucked around with this message at 13:48 on Feb 6, 2023

Ihmemies
Oct 6, 2012

I have asked the question in every course - why does the tester use some old version of the language?

The answer has always been that the version X of the language offers the neccessary tools to solve the exercises.

Well, yes, thanks.

giogadi
Oct 27, 2009

Ihmemies posted:

I have asked the question in every course - why does the tester use some old version of the language?

The answer has always been that the version X of the language offers the neccessary tools to solve the exercises.

Well, yes, thanks.

Know that I’m very angry for you

Dijkstracula
Mar 18, 2003

You can't spell 'vector field' without me, Professor!

giogadi posted:

Know that I’m very angry for you
big same - when I was a lab instructor for a course like yours I got a similar response (the instructor had, I'm convinced, never programmed in C in any meaningful capacity) and I'm still mad about it

first thing I did when I taught the class was to throw out the ancient textbook that treated the ansi standard like they'd just cracked the technology and said "your baseline language version is now --std=gnu99, good luck have fun"

leper khan
Dec 28, 2010
Honest to god thinks Half Life 2 is a bad game. But at least he likes Monster Hunter.

Dijkstracula posted:

big same - when I was a lab instructor for a course like yours I got a similar response (the instructor had, I'm convinced, never programmed in C in any meaningful capacity) and I'm still mad about it

first thing I did when I taught the class was to throw out the ancient textbook that treated the ansi standard like they'd just cracked the technology and said "your baseline language version is now --std=gnu99, good luck have fun"

There's nothing wrong with C89

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
Academia coding has certain cultural similarities to electrical engineering coding. A friend of mine summed the fundamental problem very well though: "The first way I learned is the best way."

In other news:

leper khan posted:

// There's nothing wrong with C89

Adbot
ADBOT LOVES YOU

giogadi
Oct 27, 2009

It’s fine but don’t force your students to use it

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply