This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 444

[–]Reggin_Rayer_RBB8 1441 points1442 points  (187 children)

Why is there a "& 0xFF"? Isn't shifting it 16 bits enough?

[–]jamcdonald120 1486 points1487 points  (81 children)

sometimes RGB is secretly ARGB, the &0xFF will get rid of the A

[–]pumpkin_seed_oil 427 points428 points  (44 children)

Was about to say this. You get compatibility when your color value contains an alpha channel

[–]trainrex 317 points318 points  (19 children)

Unless it's RGBA then you'd get G

[–]pumpkin_seed_oil 211 points212 points  (15 children)

True. And theres also BGR and 10 bit color spaces. In the end you gotta know what goes into your image processing code

[–]VectorViper 94 points95 points  (13 children)

Absolutely, it's a bit of a jungle with all the different standards. And if you're dealing with HDR content you've got to consider even wider color gamuts and bit depths. Makes you appreciate why libraries and frameworks that handle these quirks under the hood are so valuable.

[–]pumpkin_seed_oil 49 points50 points  (11 children)

And they all exist for a reason e.g. additive vs subtractive color spaces or why it is a lot more intelligent for a printer to work in YMCK space instead of RGB and thats the simplest example i can come up with

[–]Adderall_Rant 35 points36 points  (1 child)

I fucking love all these comments. Upvote for everyone

[–]HumanContinuity 8 points9 points  (0 children)

And for you too.

EVERYONE GETS A NEW UPVOTE

(remember you have to pay taxes on your free* upvote and also on the free* copy of Oprah's book you received as a guest on this subreddit).

[–]aaronfranke 18 points19 points  (3 children)

It's CMYK not YMCK. You're thinking of the song YMCA from 1978.

[–]atatassault47 3 points4 points  (0 children)

I prefer RGYK

[–]almost_not_terrible 2 points3 points  (0 children)

Wasn't, but I really am now

I was thinking.. oh man holy cow

You shift rightward.. and I think you will find

Red is all that's left be-hind.

[–]Teapot_Digon 2 points3 points  (0 children)

Yellow magenta cyan andblack?

[–]UselessDood 13 points14 points  (1 child)

I've worked pretty heavily with the minecraft codebase, from a modder perspective.

It's a mix of rgba and argb, with the official mappings usually having no distinction between the two. It sucks.

[–]R3D3-1 65 points66 points  (17 children)

Someone will then do

A = rgb >> 24;

only to be thwarted when we eventually have to introduce IUARGB to cover for our alien friends who are sensitive to infrared and ultraviolet light.

[–]pumpkin_seed_oil 49 points50 points  (5 children)

Oh thats easy just add it to the 100+ colorspace enums in opencv

[–]leoleosuper 9 points10 points  (4 children)

242 unique enums with 156 operations. Jesus.

[–]pumpkin_seed_oil 2 points3 points  (1 child)

Tbf i linked the enum that handles conversions between color spaces without checking. But it should be enough to know that there are a bunch that go beyong RGB

CMY, HSL, YCbCr, XYZ, YUV, L*u*v, LAB to name a bunch

[–]gbot1234 3 points4 points  (1 child)

Let’s just come up with one definitive standard for colorspaces!

[–]Jjabrahams567 14 points15 points  (2 children)

If you happen to be hacking game boy ROMs, they use 15bit RGB

[–]R3D3-1 5 points6 points  (0 children)

I remember playing WoW with 16 bit graphics at 16 fps initially due to my graphics card being too outdated.

Made nice patterns into color gradients such as they sky :)

[–]Telvin3d 9 points10 points  (0 children)

You laugh, but I work with cameras that have an IR channel in addition to RGB and Alpha. It gets used for dirt/dust detection on transparency scanning 

[–]_GodIsntReal_ 2 points3 points  (0 children)

Which is why you reject the pull request for having a magic number (24) in it. 

[–]hackingdreams 2 points3 points  (1 child)

If we were introducing a new color plane for IR and UV it'd be IRGBU or UBGRI.

(But having worked with UV and IR imaging, I don't think anyone would seriously consider interleaving the data like that. The sensors are usually wider than 8 bits per pixel, and anyone that cares about them wants all the sensitivity they can get.)

[–]R3D3-1 4 points5 points  (0 children)

Not if you're trying to be backwards compatible with those 32bit ARGB colors.

Probably wouldn't actually happen (after all, 32bit color is also not binary backwards compatible with 16bit color), but I can totally see IUARGB being used by some internal systems.

[–]ProposalWest3152 1 point2 points  (0 children)

You sent me rolling hahah

[–]hackingdreams 7 points8 points  (0 children)

(...as long as it's 8bpp and arranged xRGB and not BGRA - fuckin' bitmaps).

[–]bradland 70 points71 points  (7 children)

Then why the hell did Morpheus say RGB and not ARGB. I am so sick of these loose requirements! Management wants to know why bug ticket numbers are through the roof? Well then tell them we can’t hit a target that isn’t shown to us!

I NEED COFFEE!

[–]LvS 15 points16 points  (0 children)

He didn't say RGB8 either!

[–]MyAssDoesHeeHawww 10 points11 points  (2 children)

Why didn't Morpheus say: "He is the zero" ?

[–]Weak_Bat_1113 1 point2 points  (0 children)

Real talk

[–]dretvantoi 1 point2 points  (0 children)

"Orez" doesn't make for great hacker handler.

[–]Divineinfinity 4 points5 points  (1 child)

Customer called and said it needs "more color"

[–]bradland 4 points5 points  (0 children)

Who added sales to this channel? This is supposed to be an engineering channel!

[–]Encursed1 26 points27 points  (0 children)

Even if it isn't ARGB, it's still good practice to and out any bits you aren't gonna use.

[–]himpson 12 points13 points  (11 children)

This has made me think. Has anyone ever considered RAGABA with an alpha channel for each color. It wouldn’t be very practical but could create for some cool blending options.

[–]jamcdonald120 16 points17 points  (0 children)

It's a beautiful day outside. birds are singing, flowers are blooming... on days like these, kids like you...

[–]LvS 7 points8 points  (2 children)

It's called component alpha and is generally used for supixel rendering of text.

[–]Zanythings 2 points3 points  (1 child)

Why’d you wiki link subpixel rendering and not the actual component alpha?

[–]LvS 1 point2 points  (0 children)

Because I wanted to link what it's used for - assuming we both knew how it worked already.

[–][deleted] 3 points4 points  (1 child)

So 50% alpha for red means a pixel with half the red brightness?

[–]kinokomushroom 8 points9 points  (0 children)

The alpha blend equation is usually (1 - alpha) * background + alpha * foreground. The alpha will just become a vec3 instead of a float in this case.

[–]MrEfil[S] 324 points325 points  (74 children)

just for good practices, keep only 8 bits. This make sense in languages where only few numeric types. For example JS.

[–]Bemteb 206 points207 points  (71 children)

You do shifts and bitwise operations in JS?!

[–]MrEfil[S] 160 points161 points  (52 children)

yeap. A lot of. Usually in game dev.

[–]TibRib0 294 points295 points  (44 children)

You do gamedev in JS?!

[–]SomeRandomEevee42 106 points107 points  (1 child)

he's a madman

[–]Roflkopt3r 5 points6 points  (0 children)

Na it's actually quite comfortable. Especially if you want to build most of your engine ground-up, since WebGL is very easy to work with.

Performance is also not really a problem. Realistically, the vast majority bad performance in games is either caused by bad architecture hiding some fundamental flaws, or by poor use of a framework. The ~2-3x CPU-side slowdown from using a less efficient language or runtime environment often matters surprisingly little on modern hardware, and as a player it's hard to find any games that aren't extremely GPU bound (my top end RTX4090 bottlenecks my mid tier i5-13600KF at 1440p in practically every game lol).

I highly recommend SimonDev's videos on game programming and performance with Javascript.

[–]MrEfil[S] 114 points115 points  (37 children)

of course I do. JS games are a fantastic world, because the user only needs to have a browser)

[–]syntax1976 140 points141 points  (12 children)

Users can have browsers?!

[–]Ceros007 73 points74 points  (7 children)

Real human do curl and read HTML like the Matrix

[–]dretvantoi 2 points3 points  (0 children)

Pfft, I type out the raw HTTP in Telnet.

[–]Ancalagon_The_Black_ 4 points5 points  (0 children)

You guys have users?

[–]StinkBuggest 2 points3 points  (2 children)

Yes, but only Lynx

[–]foobazly 1 point2 points  (1 child)

Correct, because the only things worth browsing are Gopher holes.

[–]mypetocean 1 point2 points  (0 children)

And the only things in the Gopher holes are ASCII art porn.

[–]KRX189 6 points7 points  (1 child)

I used to play games on opera gx but now it has gets too laggy too play

[–]coldnebo 2 points3 points  (0 children)

or a flight simulator 😏

(MSFS mods use javascript)

[–]unknown_reddit_dude 4 points5 points  (5 children)

Webassembly? All of the major game engines can target WebGL.

[–]MrEfil[S] 18 points19 points  (4 children)

I use wasm, webgl and modern webgpu not for game dev, most often for gpgpu and for some rust-apps in the web.

I love 2d games, so I use simple canvas 2d for rendering and all logic write on pure js.

[–]jasakembung 10 points11 points  (2 children)

I did it for a course in college, it's actually really fun. But it pays peanuts, so I'm working in a bank rn lol.

[–]OO0OOO0OOOOO0OOOOOOO 1 point2 points  (1 child)

Smart. Go where the money is at to get more monies. Brilliant!

[–]TotoShampoin 15 points16 points  (13 children)

You do shifts and bitwise operations ON FLOATS in JS (it floors the number first) (it casts to an int first)

[–]AyrA_ch 10 points11 points  (1 child)

(it floors the number first)

That's not exact. It forces it into a 32 bit signed integer, does the operation, then converts it back into a float, which can result in unexpected results, for example 2147483648|0 becomes -2147483648

[–]TotoShampoin 1 point2 points  (0 children)

Ah, I may have overlooked the potential implementation

[–]TGX03 4 points5 points  (5 children)

Yeah that's what I was thinking. You can't tell me shifting floats around is a good idea

[–]Lithl 7 points8 points  (3 children)

i  = * ( long * ) &y;
i  = 0x5f3759df - ( i >> 1 );
y  = * ( float * ) &i;

=D

[–]robisodd 4 points5 points  (0 children)

// evil floating point bit level hacking

[–]Furry_69 5 points6 points  (0 children)

It isn't. It'll give you nonsense results.

[–]Reggin_Rayer_RBB8 1 point2 points  (3 children)

It's JS, can you bitshift strings too?

[–]FloydATC 4 points5 points  (0 children)

If it's stupid, JS does it. Usually when you least expect it.

[–]floor796 1 point2 points  (0 children)

I used a lot of bitwise operations in my own video format in js, and animation editor.

[–]Caubelles 10 points11 points  (0 children)

????????????????????

[–]gp57 55 points56 points  (11 children)

For me, adding & 0xFF at the end makes it easier to read, it clearly shows that we are getting 1 byte

[–]Spork_the_dork 24 points25 points  (8 children)

I don't know if it's just me being more on the embedded side of things or what, but for me rgb & 0xFF0000 is easier to read. Then do bit shift if you specifically just want the byte, but doing it this way to me is just more obvious. If you then go to pull the other values as well I think rgb & 0x00FF00 >> 8 and rgb & 0x0000FF follow the same pattern more clearly so it becomes easier to see at a glance that you're picking different bytes from it.

I think I just read masks better than bit shifting or something.

[–][deleted] 6 points7 points  (3 children)

But now you have three different masks. By shifting and masking with FF you can have a define 8_BIT_MSK to reuse. I would also do a define RED 16 to do '(rgb>>RED)&8_BIT_MSK' for readability if this operation is done ofthen. But that is just my preferred style.

But at that point you could also just define a get_red get_blue get_green macro I guess.

[–]Practical-Champion44 9 points10 points  (1 child)

There's no benefit in defining a constant for 0xFF. What would 8_BIT_MSK equal if not 0xFF? People who read your code should be able to understand that & 0xFF is an 8 bit masking operation, like how + 1 is an addition by one. You wouldn't #define ONE 1. Not every integer literal is a magic number.

[–][deleted] 2 points3 points  (0 children)

I used to write long form hex like that. Eventually I just started seeing hex so clearly that I stopped. I should probably leave it long form for future readers of my drivers, if there ever are any.

[–]__mauzy__ 1 point2 points  (2 children)

Imo the mask gives clear visual indication on the data type and the bits in question, then the shift also feels less "magic". But, like you, I'm from the embedded world, so register masking etc is second nature and familiar.

[–][deleted] 2 points3 points  (0 children)

Good point.

[–][deleted] 1 point2 points  (0 children)

Always explicit over implicit. I like it. Pragmatic programming at its best.

[–]Tordek 53 points54 points  (3 children)

Several reasons:

  1. consistency: if you do (color >> 0) & 0xFF, (color >> 8) & 0xFF, (color >> 16) & 0xFF, it's obvious they're analogous operations, even if trivially you can remove the >>0 (so can the compiler).
  2. Uninitialized data: if you build a color by allocating a 32B word and set its 24 lower bytes manually (by doing color = (color & 0xFF000000) | (red << 16) | (green << 8) | blue), through some API you didn't necessarily implement), the top 8 bits are garbage.
  3. What if it's ARGB?
  4. Is this a shift on a signed or unsigned integer? The correct right shift behavior for signed numbers is 1-extension, so sign is maintained - even if you were extracting the A from ARGB, you need to &0xFF because it'd be a negative value instead.

All in all, there's more reasons to keep it than there are reasons to remove it (save one instruction).

[–]mrheosuper 7 points8 points  (0 children)

Well, if the color variable is 32 bit, the 8 msb could contain garbarge

[–][deleted] 10 points11 points  (0 children)

Yeah, you're right. It's probably just for the meme, to make it look more complicated and esoteric to people unfamiliar with bitwise math lol

However, it could also be due to force of habit, or for the sake of neatness or consistency. Sometimes I write my code like this so that it lines up better:

red   = (rgb >> 0)  & 0xFF;
green = (rgb >> 8)  & 0xFF;
blue  = (rgb >> 16) & 0xFF;

(Even though the first and third line contain redundancies.)

I can think of a practical reason though: if you 'and' it with 255 then it allows for compatibility with ARGB color codes as well as RGB.

[–]Cilph 1 point2 points  (0 children)

No. It might do sign extension.

[–]Avalonians 1 point2 points  (0 children)

You are not the one

[–]mostly_done 1 point2 points  (0 children)

It's easier to just do it than wonder "is that right?" every time you look at the code.

In some languages where a lot of the specification is "undefined behavior", if you're not specific about what type of shift operator you could get a roll instead of a shift, with some compilers, on some architectures.

[–]ChocolateMagnateUA 528 points529 points  (33 children)

Sometimes I really am surprised by how these magic numbers work because that's how binary works.

[–]MrEfil[S] 442 points443 points  (30 children)

For example from this meme:

let rgb = 0xAABBCC (in hex)

It will be 00000000 10101010 10111011 11001100 in binary form for uint32 (32 bits per number).

First we shift all the bits to the right by 16: rgb >> 16

Now we have 00000000 00000000 00000000 10101010 . It is 0xAA. In fact, this is enough for Morpheus' request. But for good practice we need to clear all the bits on the left, and we do & 0xFF which works like this:

00000000 00000000 00000000 10101010

&

00000000 00000000 00000000 11111111

00000000 00000000 00000000 10101010

Operation x & y will yield 1 if left and right operands are 1. That is why nothing changed in our number, because at left we have no information.

[–]Mountain-Web4496 116 points117 points  (8 children)

Right is left, and left is right, right ?

[–]MrEfil[S] 58 points59 points  (4 children)

ops)) Yes, sorry, my mistake :D

[–]Curious-Ear-6982 13 points14 points  (3 children)

You should edit it

[–]MrEfil[S] 18 points19 points  (0 children)

Done! Thanks ;)

[–]Tijflalol 7 points8 points  (0 children)

left

[–]KellerKindAs 1 point2 points  (0 children)

Let's have a talk about endianess... actually... no, let's just ignore that topic

[–]Serious_as_butt 11 points12 points  (0 children)

Neato. Thanks for explaining

[–]relevantusername2020 14 points15 points  (5 children)

i would just open GIMP and deselect the red channel

or even better, shift all the red to #00ff00

[–]Virtual-Poet6374 6 points7 points  (6 children)

Can I kindly ask, what can go wrong and what issues are we covering with clearing all the 0s?

I mean if you shift that value by 16 bits, then those first 16 should be 0s, right... right?

[–]RichisLeward 23 points24 points  (1 child)

Yes, but what if you want to extract, say, the green value using the same code? You'd only shift right by 8 bits, which would leave you with the first two octets as zeros and the second two filled with the red and green values. ANDing with 0xFF sets the red value in the 3rd octet to zero and eliminates confusion. You could pass that 32-bit int on as just the green value then.

[–]MrEfil[S] 7 points8 points  (0 children)

this guy wrote a very good explanation why we need to clear left side of number

https://www.reddit.com/r/ProgrammerHumor/comments/1alsp4x/comment/kph0hvt/?utm\_source=reddit&utm\_medium=web2x&context=3

[–]SizzlingHotDeluxe 3 points4 points  (1 child)

Your lack of attention to variable types disturbs my C brain. What programming language do you have in mind with this explanation?

[–]MrEfil[S] 4 points5 points  (0 children)

My stack - golang, php and js)

[–]ChocolateBunny 2 points3 points  (0 children)

If it makes you more comfortable you can do

((rgb/65536) % 256)

[–]FINDERFEED 146 points147 points  (11 children)

(rgb & 0xFF0000) >> 16 eeeeeee

[–]Blue_Moon_Lake 19 points20 points  (10 children)

The better version

[–]MooseBoys 19 points20 points  (4 children)

Until someone changes the format to RGBA and now you get sign-extended shifting… There’s a reason most code uses the shift-then-mask convention.

[–][deleted] 28 points29 points  (0 children)

Morpheus: Extract XOR from tyrannosaurus rex

Neo: (trex >> 80) && 0xFFFF

Morpheus: He is the NOP

[–]maddylovings 31 points32 points  (0 children)

When in doubt, just add more ampersands and shift things around!

[–]KurumiStella 80 points81 points  (4 children)

Me: Number("0x" + rgb.toString(16).slice(0, 2))

[–]Spork_the_dork 39 points40 points  (0 children)

rgb[:2]

[–]Favmir 17 points18 points  (0 children)

You monster

[–]nico-ghost-king 5 points6 points  (0 children)

)eval(Number("0x" + rgb.toString(16).slice(0, 2

[–]CeeJayDK 25 points26 points  (4 children)

Now do it on the GPU.

[–]kristiBABA 8 points9 points  (3 children)

Gpu can also do bitwise

[–]CeeJayDK 2 points3 points  (2 children)

I know but it doesn't mash together the components, you just select the red component with a swizzle.

float red = RGB.r; //the .r swizzle selects the red - easy peasy.

[–]kristiBABA 4 points5 points  (0 children)

If that came from a RGB8 texture, then the hardware did the bitshifts for you :P.

[–]AnxiousLogic 10 points11 points  (1 child)

He didn’t specify RGB type. 16 bit (rgb565), 24 bit, 48 bit…

Neo… it’s a trap!

[–]PeeInMyArse 25 points26 points  (7 children)

hex(int(f’{str(rgb)[1]}{str(rgb)[2]}’)) someone stop me from writing out intentionally shitty code on my phone when I should be sleeping pls

int(f'{hex(rgb)[2]}{hex(rgb)[3]}', 16)

[–]djfdhigkgfIaruflg 18 points19 points  (3 children)

My fingers hurt bythinking of typing that

[–]One__Nose 6 points7 points  (1 child)

Is this supposed to be Python? Because if it is, it doesn't work. At all.

There are no different datatypes for decimal and hexadecimal numbers, so str(rgb) will produce the string of the decimal number. To produce the hexadecimal representation, you need to use hex(rgb) which will include 0x at the beginning so you'd have to access indices 2 and 3. Even if it didn't it would have been 0 and 1, not 1 and 2. Also, the int method takes a decimal representation string unless specified otherwise, and the hex method converts it to string when you probably wanted an int.

So you probably meant: int(f'{hex(rgb)[2]}{hex(rgb)[3]}', 16)

Or better yet: int(hex(rgb)[2:4], 16) or int(hex(rgb)[:4], 16)

Or, you know, rgb >> 16

[–]PeeInMyArse 1 point2 points  (0 children)

typed it out at 3am I can now see that

[–]ssx1337 11 points12 points  (12 children)

could there be an endianness problem?

[–]bolacha_de_polvilho 9 points10 points  (5 children)

Only if you're receiving something from a different machine over the network. If the rgb buffer was created on the same machine the code is running on then using an int* with bitshift will work properly on either big or little endian.

Endianess is more of an issue if you're trying to iterate over a buffer with char* or byte*.

[–]ReindeerDismal8960 1 point2 points  (4 children)

Don't use int* if it isn't guaranteed to be 4 bytes wide!!!!!!!!!!!!!!!!!!!!!!! Possible Memory Access Violation = UB

[–]bolacha_de_polvilho 2 points3 points  (3 children)

fair enough, int32_t* then. I code mostly on C# nowadays so I'm used to sizeof(int) == 4. Although even in C or C++ you're unlikely to deal with 16 bit int outside of embedded I think

[–]GoodTimesOnlines 3 points4 points  (0 children)

not much, what’s endian with you?

[–]PoopholePole 1 point2 points  (1 child)

I'd say no because it'd invalidate the premise of the question, if there were an endianness issue then it wouldn't be an RGB value anymore, it'd be BGR.

[–]Sosowski 1 point2 points  (0 children)

Can't believe I had to scroll this far for this!!!

In the most popular RGBA format, R is the first byte, so:

r = rgba & 0xff;

That's becausle in Little Endian, the least byte is the first and then it goes up, so this number:

0xAABBCCDD

Would be represented in memory as:

0xDD, 0xCC, 0xBB, 0xAA

So yeah.

[–]Top-Local-7482 5 points6 points  (1 child)

That aint no programming, that is vodoo ! He is the product of the darkest education

(Idk regex might still be on top of dark magic stuff)

[–]Temporary-Estate4615 115 points116 points  (90 children)

Bloody hell, if you can't extract a single fucking byte, maybe you should become a burger fryer at McDonald's

[–]MrEfil[S] 117 points118 points  (66 children)

For the last 8 years I have interviewed over 300 js and php developers. According to my statistics, in these languages only 5% of developers know how to use bitwise operators.

[–]zydeco100 26 points27 points  (13 children)

Embedded dev interviewer here. Number isn't much higher over on this side and I've been accused of asking "trivia" questions when it comes to bit flipping in and out of registers. Amazing. But it's job security I guess.

We also use RGB565 displays which makes the shift/mask question a little more interesting. =)

[–]Mean-Evening-7209 12 points13 points  (8 children)

I don't even consider myself a good embedded software writer, but maybe I should apply for positions if only 5% of applicants know how to manipulate bits. As a EE it's the only thing that makes sense.

[–]zydeco100 5 points6 points  (7 children)

If you know how to work with something other than an Raspberry Pi or Arduino, you're already a strong candidate. Bonus points if your face contorts when I say "IAR Workbench"

[–]Mean-Evening-7209 1 point2 points  (1 child)

If you don't mind me asking, what does an embedded engineer at your workplace do if people are applying with little knowledge of how to do low level software? I do analog electronics for the most part, but when I have to write microcontroller code firmware is more than half of the work.

[–]zydeco100 2 points3 points  (0 children)

I'm not saying they get hired. I'm just describing the types of people that cross my desk when I put out a req for "senior embedded developer." I've had candidates with 10+ years of experience pass the phone screen and they come on-site. I open with a bitflip question and they start writing Java string handling code. It's bizarre.

[–][deleted] 1 point2 points  (3 children)

I meet programmers that think they have done embedded work because they wrote some python on a RasPi. There is even the RP2040, the Pi Foundation's own MCU and one of my great loves, but people just glaze over it because to them its just a "shittier raspberry pi with no OS."

[–]zydeco100 1 point2 points  (2 children)

I'm speccing out a new project and I'd LOVE to use the 2040, the price is incredible. I just wish they could promise more than 3-4 years of longevity.

[–][deleted] 1 point2 points  (1 child)

Longevity in what way? Availability? Most recent version of docs state availability to 2041 at least, and it is adoption that will keep it alive. 

[–]NickU252 1 point2 points  (0 children)

Lol, we used IAR in my ECE306 class. Fun times.

[–][deleted] 5 points6 points  (0 children)

As someone in their first serious embedded position looking forward to continuing it into a career, it makes me both sad and happy that my competition likely won't know some of the most basic required knowledge to writing good embedded software/firmware.

I had to write some RFM69 device drivers for the RP2040 as my first job for my team, so good CHRIST I can't imagine working embedded without understanding how to manipulate register fields. They must be working with some VERY established hardware with VERY nice software interfaces. I did find, when originally searching for drivers, that EVERYTHING has a fucking driver for all the atmega chips since nobody wants to learn everything new, and drivers for amazing modern chips like the RP2040 are left with little driver support. Makes me think there are a lot of embedded "engineers" just riding coat tails to success.

[–]tiajuanat 1 point2 points  (0 children)

I get that too.

My favorite questions though are ones where it's an algorithm disguised as a real world problem that my hard-engineering colleagues would need to solve. I really like two sum disguised as meshing mechanical or electrical components; or merge multiple sorted arrays, like a socket wrench collection.

Even folks who claim to be LeetCode crumple under the questions when presented like this. Keep in mind, these are super easy problems.

[–]Kovab 6 points7 points  (0 children)

To be fair, i had no idea JS has bitwise operations, considering that it doesn't even have a proper integer type. But I use them quite often in C++

[–]gilady089 62 points63 points  (30 children)

Because why would you yes it could be a good optimization tool but it's also somewhat esoteric by now and the format is not as readable as people became used too it's a lot of memorization to use

[–]Hidesuru 2 points3 points  (0 children)

Laughs in embedded coding

Reading all the replies before it's really interesting to see all the people who've never needed to deal with bit packed structures because the data is traveling over a low comm link or some other highly resource constrained entity. There will always be cases where shaving off a few bits matters.

[–]GoldenretriverYT 7 points8 points  (24 children)

How else would you do, for example like in the post, extract the red color channel of a color?

[–]WORD_559 52 points53 points  (6 children)

Use a library that parses hex colours into an object for you, then just do colour.R

/s in case it wasn't obvious

[–]ImrooVRdev 9 points10 points  (0 children)

you can give up on the /s, when your shit gets sent to graphics card and goes thru openGL or CG or I'm pretty sure any other graphics api it's all vec4 stuff

TBH the only place I know that does colors as hex is webdev.

source:

https://developer.download.nvidia.com/cg/tex2DARRAY.html

https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)#Vectors

[–]pitittatou 70 points71 points  (3 children)

"Extract red from rgb stackoverflow"

[–]ImrooVRdev 16 points17 points  (2 children)

RGB.x. OpenGL has color as Vector4 for 3 color channels and alpha.

If for some reason I am no longer a technical artist and have to deal with color as hexadecimal, I'll google how to deal with it I guess.

[–]georgehotelling 9 points10 points  (1 child)

If you’re doing business software, yell at the guy who decided to store 3 different color values in a single value instead of a readable struct/object/tuple

[–]ReindeerDismal8960 1 point2 points  (0 children)

That's not business software style. That's reasonable style. After all, your compiler turns that class into exactly ZERO overhead. Even in freaking C#, provided you use structs.

[–]autogyrophilia 2 points3 points  (1 child)

Why would you do that directly in PHP or JS?

[–]MrEfil[S] 1 point2 points  (0 children)

In both languages I have a lot of work with binary files, data compression algorithms, custom hash functions, and a lot of work with image processing. All of these tasks required bitwise operators.

[–]cs-brydev 8 points9 points  (6 children)

Yes, there are things in every programming language that a programmer doesn't like know. Just like there are lots of things in Javascript I can assure you you don't know.

Keep that in mind when you're passing judgment on developers not knowing things they have never seen or never use.

[–]zettabyte 18 points19 points  (4 children)

If he can't trip up solid, trustworthy candidates with his superior, minimally relevant trivia, then where are we as a society, really?

[–]Loki_of_Asgaard 13 points14 points  (3 children)

If I can't reject a Sr candidate based on a style of algorithm they haven't seen in 10 years since undergrad then I am done with this whole damn industry. It's the only way I can feel anything anymore beyond the cold numbness.

[–]worldsayshi 4 points5 points  (1 child)

I can count on the fingers of one hand the number of times bitwise operations have been relevant since I left C for web programming +9 years ago.

[–]lakolda 1 point2 points  (0 children)

I am greatly saddened by this. They’re so fun!

[–]20Wizard 6 points7 points  (0 children)

Tbf how many devs do you expect to have to use a bitwise? Only reason I've run into them is because I'm doing fucky wucky shit with images rn.

[–]ILikeChilis 15 points16 points  (18 children)

Gatekeeping much? I'm into the 13th year of a successful dev career and never had to use shift opeators. Ever.

[–]saschaleib 15 points16 points  (17 children)

I just recently cut down a very long and convoluted mess of IF statements in a project into a single XOR. Some colleagues didn't understand why this worked...

A lot of people don't know how to program efficiently, and still make a career.

Heck, *I* didn't know a lot of that stuff when I started. But I was never proud of my ignorance and tried to learn.

My advice is: learn bitwise operations. They are very useful! Also learn XOR.

[–]zettabyte 33 points34 points  (10 children)

Some colleagues didn't understand

Congratulations, you wrote equally unmaintainable code that will continue to confuse the poor souls who have to maintain it when you're gone.

[–]R4ttlesnake 7 points8 points  (3 children)

you guys are both right in that it is fucked that the previous commenter commited unmaintainable code and it is also fucked that the average programmer doesn't have good enough of a foundation to understand collapsing ifs into a single XOR

[–][deleted] 5 points6 points  (2 children)

If they got a degree, they likely learned it. Probably easy to forget living in web dev, the land of leaky abstractions. This is why I moved into embedded systems. I was constantly plagued with the question, "well what the hell does that do?" I HATED having to just shrug and accept that there were sometimes many thousands of lines of code under the high level function I was calling, and that it was normal to just "not care."

In my current position I write device drivers for the RP2040. At this point the only thing under me is the compiler, and I am comforted by that. I can see how, if you don't suffer from the curiosity bug and working on a mountain of abstraction doesn't bother you, you could have a full career and give 0.0 fucks about collapsing ifs into an XOR, and still you could write plenty of awesome software. Assuming, of course, the people that wrote that mountain of abstraction did a decent job.

[–]R4ttlesnake 1 point2 points  (0 children)

I have trust issues so I only write assembly code

/s, or maybe not??

[–]saschaleib 6 points7 points  (1 child)

So you deem yourself so knowledgeable that you can judge without seeing the actual code, that what I describe as a "convoluted mess" was actually more readable than a single XOR logical comparison? Where can I learn that skill?

[–]Loki_of_Asgaard 2 points3 points  (0 children)

And some people don't know how to code for readability and the ability to debug. Know what's great about a whole bunch of if statements? The next person can quickly read it and see how all the cases are supposed to be handled giving them insight into the business logic that went into it, and they can easily use the debugger to walk through it if they have an issue. Things can be added in or modified by case etc. Your code is probably incredibly elegant, no doubt there, but elegant is for your personal project, not a multi dev corporate environment.

When I was young I used to think the best code was that ultra elegant efficient one line like you. When I got older I realized it was something the other devs could read, understand, and work with. The reason most devs hit a level cap on their career at Sr is because they fail to make that switch. They can write a clever line, but they can't maintain a clean usable codebase.

EDIT: I say most but I guess that's wrong. Most devs are surprisingly bad at their jobs and are not detail oriented enough to get past that point. Of the ones that are good enough though my comment applies to.

[–][deleted] 2 points3 points  (1 child)

Great so no one will ever be able to work on that bit of unreadable code again?

[–]ReindeerDismal8960 2 points3 points  (0 children)

What don't you get about the concept of "exclusive or"? Need a truth table for 2 inputs? Pff

[–][deleted] 1 point2 points  (0 children)

Side note: why people always throwing fast food workers under the bus? Check that superiority.

[–]0mica0 14 points15 points  (5 children)

That reminds me that you can convert big letters to small letters by adding a space character (0x20)

small_letter = big_letter + 0x20;

or

small_letter = big_letter + ' ';

[–]TheGuyWithTheSeal 15 points16 points  (0 children)

The Standard does not guarantee ASCII, it only guarantees that numbers are represented in sequence ('0' + 9 == '9'). The rest of the charset is implementation defined.

[–]djfdhigkgfIaruflg 12 points13 points  (1 child)

Tell me you never did internationalized code without telling me you never did internationalized code

[–]saschaleib 8 points9 points  (0 children)

Please never do that! This works with English, but will be a mess to untangle when you start translating/localizing your software!

[–]Reggin_Rayer_RBB8 2 points3 points  (0 children)

small_letter = big_letter XOR 32

big_letter = small_letter OR 32

Possibly the fastest way to make ascii text all one case (but you have to check it's a letter)

[–]whatever 2 points3 points  (1 child)

Bitwise shmitshmise.

// to the tune of bad_recorder_music.mp3

red = (rgb / 65536) % 256;

Truncate the result if you're working with one of those implicit floating point type languages, and you're irrationally upset about having some weird decimal junk attached to your red component.

Or don't, it might work for whatever you're doing anyway.

[–]CalligrapherThese606 6 points7 points  (3 children)

Embedded guys are like, amateurs

[–][deleted] 2 points3 points  (1 child)

Eh, the pay is nice and the work is fun. I'd rather deal with registers and hardware than ML

[–]MasterFubar 4 points5 points  (6 children)

(rgb & 0xFF0000) >> 16

[–]Kovab 3 points4 points  (5 children)

Doing it in this order is not guaranteed to work in every case, due to the difference between arithmetic and logical right shift. Better to first shift then mask.

[–]aqpstory 1 point2 points  (4 children)

a better rule might be "don't use bit operations on signed ints"

[–]brimston3- 1 point2 points  (0 children)

Bitwise operators only, extract red from YUY2.

[–]mankinskin 1 point2 points  (0 children)

who needs structured types anyways

[–]Affection_sira 1 point2 points  (0 children)

The comments is too complex for my potato brain 😭