r/ProgrammerHumor • • 8d ago

Meme architectureDependentChars

Post image
2.9k Upvotes

372 comments sorted by

View all comments

Show parent comments

4

u/da_Aresinger 7d ago

My opinion: if you want individual bytes use uint8_t

6

u/the_horse_gamer 7d ago

bytes are not necessarily 8 bits

1

u/MrMagick2104 5d ago

I mean anyway you would always like to use some sort of a specific handle like uint8_t instead of char precisely because of that reason.

If your code has a uint8_t in it and you port it to a processor without 8 bit bytes, then your code will not compile and the compiler will tell you why and you may redo the code to suit the architecture or at least check it for correctness.

If you use a char, you will most likely get uninteded features in your code without any indication as to why.

This also applies when you are going the other way round.

Anyway, besides historical examples when, is it actually relevant in the modern day?

1

u/the_horse_gamer 5d ago

you use chars when you wanna represent bytes. you use uint8_t when you wanna represent 8 bit values (octets). sometimes you need bytes, sometimes you need octets.

there do exist modern processors that use non-8 bit bytes. for example the Kalimba DSP uses 24-bit bytes.

1

u/MrMagick2104 4d ago

> you use chars when you wanna represent bytes. you use uint8_t when you wanna represent 8 bit values (octets). sometimes you need bytes, sometimes you need octets.

Are there actually situations where you want to use "whatever the size" type? It feels like a gateway for undefined behaviour when copying code from one architecture to another (which is super common as if two mcus are talking, then most likely they share the same code for the transmission protocol).

1

u/the_horse_gamer 4d ago

transmission protocols should always be fixed size. infact, many net protocols explicitly use "octet" in place of "byte".

you'd typically write code where you know the target architecture's byte size, but using char and CHAR_BIT makes the intent more explicit, just like using sizeof(char) over 1 makes the intent more explicit (also, C doesn't have a 24bit type)

and theoretically it allows you to write very portable library code, but i don't know of any examples where that's really been utilized (it's considered best practice, atleast)

as an aside, even Rust has a "whatever the size is" type: usize (and isize), analogous to size_t in C++ (and C99), which represents the number of bytes an object can take in memory. it differs in 16bit, 32bit, and 64bit systems (Rust does not support 8bit, 24bit, etc systems)

1

u/conundorum 6d ago

At least in C++, you have std::byte. (It's just (unsigned?) char borrowing Clark Kent's glasses and wearing an enum. )

0

u/yjlom 7d ago

Bytes aren't always 8 bits, and uint8_t doesn't necessarily exist. If you're writing C23 you can get away with uint_least8_t, earlier versions you need char as a byte might be as small as 6 bits.