Skip to main content
gamedev.net
🔒 Locked

byte array to an integer issue

Started by dmatter 0 replies 650+ views
Original Post
dmatter
dmatter
I'm attempting to load a file to an int8_t array, with this array I want to extract the actual field values individually into numerous int_fast32_ts and int_fast16_ts. Supposing I have four bytes in the array, the difficulty is that I can't simply reinterpret_cast the array into an integer because I don't ensure a fixed size of the types (int_fast32_t only ensures that there are at-least 4-bytes, but could be more which would overrun the buffer). So I need to efficiently combine n-bytes into an (at minimum) (8*n)-bit integer but I don't know how. Possibly I need to overlay each byte into the correct position in the integer. (endianess isn't a problem at this point) but keeping in mind that the integer size isn't guarenteed to be exactly n-bytes might complicate things. note: I'm only using int_fastXX_t integers because, well, they're faster than intXX_t ones. But if all this turns out to be a greater overhead than just reinterpret_cast-ing to a non-fast integer (as was my original idea) than I'll happily change them [smile] Thanks for the help. Dave
Wyrframe
Wyrframe
int8_t data[4];
int_fast32_ts val = 0;

for (i=0; i<4; i++)
val = (val << 8) + data;

Assuming little-endian (higher address contains lower-significance byte). Unroll the loop if you desire. Change the loop order (from low-high to high-low) to switch endianess.
RIP GameDev.net: launched 2 unusably-broken forum engines in as many years, and now has ceased operating as a forum at all, happy to remain naught but an advertising platform with an attached social media presense, headed by a staff who by their own admission have no idea what their userbase wants or expects.Here's to the good times; shame they exist in the past.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.