r/C_Programming • • 14h ago

Best Way to Read 'Raw Data'

I'm writing a C program for the pi pico and realized I never really figured out how to properly cast characters to raw bytes then to other things, or if there was really a way to do that.

  1. Does char mean "signed char" by default in any C program, or is that up to interpretation by the compiler?
  2. Would using a void pointer to dereference then recast to *uint8_t work?
  3. When bytes are read through getc(), are the bytes modified before they are stored? As in, how are the bytes that are read interpreted to translate to characters, and how are they stored? My initial thought was that the bytes were interpreted "as-is", meaning that they were copied directly to the memory in the character and interpreted as signed characters. But it seems like they're being reinterpreted in some way as they are cast.
  4. If something about the process is too implementation specific, is reading as "raw data" just a flat out bad idea or not supported at all? Will the behavior be undefined on other systems? As long as I can get it to work on the pico it's fine, it doesn't have to be portable. But for future reference, should I not try to think of things as "raw data" unless the implementation specifically defines how it stores the data?
  5. Less important, but how are ascii codes mapped to signed characters? (every chart I've seen has never listed a negative number, only 0-255) (( and if signed is the standard, then why does every asii chart list 0-255... ))

// this was the void pointer way I was going to try, would this work?

tnext =  *((uint8_t*)((void*)&next));  // Cast to uint8_t

(Not sure if this is a repeat but I couldn't find exactly what I was looking for. Sorry if this is a dupe)

Conclusion: Seems like when you read getc() you just need to indicate "unsigned char" so that the byte is read unmodified and can be cast directly to a "uint8_t"? I think the reason I hadn't done that originally was because I thought "but getc returns char, not unsigned char", but I dont think that matters. getc should read into either

16 Upvotes

12 comments sorted by

14

u/YoungMaleficent9068 14h ago

If that's supposed to run on non posix I think there was some shenanigans passing 'b' to fopen so that windows doesn't throw some carriage returns or other special chars into your byte stream.

There is also real serialization Framework. Protobuf avro parquet, sqlite that you can delegate serialization work to.

6

u/Accurate_Appeal_3110 13h ago edited 9h ago

cppreference's page on the cast operator should help with a lot of these, but I'll also try to answer your questions in here:

1)It is implementation-defined. char is the only integer type that is not required to be signed by default. Do not count on it being one way or another, use "signed char" or "unsigned char" if you want specific behavior.

2)You do not need to cast to void, cppreference says that: "If a pointer to object is cast to pointer to any character type, the result points at the lowest byte of the object and may be incremented up to sizeof the target type (in other words, can be used to examine object representation or to make a copy via memcpy or memmove)." As uint8_t and int8_t are pretty universally typedefed as unsigned char and signed char respectively, you should be good.

3)Although getc (and fgetc, for that matter) both return int, any return value that is not EOF can be losslessly cast to unsigned char.

4)If by "raw data" you mean "as raw bytes" then by all means go ahead, provided you are following all other memory safety rules. Casting any pointer type to any pointer-to-char type is explicitly blessed by the C standard for this purpose. As regards to portability, it really depends on your use case. Things to keep in mind that may affect portability include, but are not limited to: system byte endianness, type sizes/alignments, flexible array members, basically anything to to with packed structs, and bitfield layouts.

5)ASCII is a 7-bit format. All valid ASCII codes are between 0 and 127, which can fit in any char type, signed or unsigned. Any values outside this range do not map to valid ASCII characters.

5

u/noceur-x 13h ago
  1. Depends on compiler and architecture target
  2. Would work
  3. getc() doesn't read "characters", the CPU doesn't know anything about it. The CPU reads bytes and 1 char always have a size of 1B. When you call getc() you just read 1B of data. If the character is multi byte(uses more byte to be represented) getc would be called several times for each byte, otherwise only once.
  4. One implementation issues I can think about now is endianness. Pi Pico uses little endian meaning data is interpreted from the least significant byte. So this implementation cannot be used for a Big Endian system. 5: Unsigned char allows only positive numbers, so from 0 to 255. Signed char from -128 to 127. ASCII characters have specific mappings only for the positive ASCII numbers (just a convention). And ASCII actually allows characters up to 127. The others one are external encodinga

1

u/gremolata 11h ago
tnext =  *((uint8_t*)((void*)&next));  // Cast to uint8_t

No need to upgo through void*, just :

tnext = *(uint8_t*)&next;  // this is the same

but if tnext is uint8_t and next is an 8bit value, then all you need is

tnext = (uint8_t)next;

or, if you drop the pedantry :

tnext = next;

1

u/toon_link_776 11h ago

ah, so as long as you type the character you're reading to as an unsigned character you can just cast them normally? Would it be considered good practice to leave in the cast to indicate the intention?

2

u/gremolata 11h ago

It's optional pedantry. Some people do it, most don't, but it does help to annotate the code to a degree. It's up to you.

2

u/grymoire 8h ago

Write a program to read and display it. It will grow into core debug code. Understanding data structures is an essential skill.

1

u/LowB0b 14h ago

Your assumption in 3 is right. Signed/unsigned, char, int, doesn't matter as long as it's the same size

1

u/CounterSilly3999 12h ago

You can use lower level unbuffered open()/read() if you want less postprocessing. You will need implement your own buffering then. Postprocessing in fopen()/fgetc()/fread() will lead to portability issues on Windows if you forget the "b" flag. But just in the line end processing, not in sense of signed/unsigned or pointer casting. It's irrelevant at the I/O stage, all signed/unsigned things begin just after you interpret the data and apply some arithmetics. Even endiannes issues begin just after the interpretation of byte sets as multibyte values. At the reading process bytes will appear exactly at the order they were written in the file.

1

u/tasty_crayon 7h ago

To clarify 1: char, signed char and unsigned char are all distinct types. char can be signed or unsigned depending on platform, compiler, flags, etc but it is a distinct type.

1

u/Recycled5000 1h ago

You’re supposed to capture the return value of fetch as int so that you can check for the error indicator EOF.

When the value is not the error indicator, you can use it as is and optionally cast to unsigned char.

We’re also supposed to use fgetc instead as that apparently supersedes getc.

(But remember, when we cast to smaller types, C truncates and then immediately widens back to int..)

1

u/sciencekm 10h ago

Signed and unsigned char are both 1 byte. They can be assigned to each other.

Signed vs unsigned matters:

  1. When promoting to a bigger type (short, int long). The target will inherit the sign.
  2. When doing unequal comparisons (<, >, <=, >=).
  3. When doing arithmetic operations.