问题
code :
s64 end_time;
struct timespec ts;
getrawmonotonic(&ts);
end_time = timespec_to_ns(&ts);
How to remove the first three bytes from end_time
and last one byte from it??
I want to store it in a uint32.
could someone tell me how to do that??
uint32 latency;
fscanf(fp, "%lu\n", latency); //fp is reading the end_time and storing in latency.
latency = (uint32) (latency >> 8) & 0xFFFFFFFF;
回答1:
How about:
u32 end_time32 = (u32) (end_time >> 24) & 0xFFFFFFFF;
Depending on your definition of first
and last
byte it could also be:
u32 end_time32 = (u32) (end_time >> 8) & 0xFFFFFFFF;
Example:
s64 end_time = 0x1234567890ABCDEF;
u32 end_time32 = (u32) (end_time >> 24) & 0xFFFFFFFF;
// end_time32 is now: 0x34567890
s64 end_time = 0x1234567890ABCDEF;
u32 end_time32 = (u32) (end_time >> 8) & 0xFFFFFFFF;
// end_time32 is now: 0x7890ABCD
Edit
After your updated question:
s64 latency;
fscanf(fp, "%lld", latency); //fp is reading the end_time and storing in latency.
u32 latency32 = (uint32) (latency >> 8) & 0xFFFFFFFF;
回答2:
I assume by "first" and "last" you mean "most significant" and "least significant", respectively.
I.e., you have the 8 bytes:
76543210
and want to map it to the 4 bytes:
4321
This is easiest done by a shift, a mask, and a (truncating) cast:
const uint32_t time32 = (uint32_t) ((end_time >> 8) & 0xffffffff);
The mask is very likely to be optimized out by the compiler but makes it very clear what's going on.
回答3:
You can do that with bit shifting. You have to shift the value 8 bits (= 1 byte) to the right, which is done with the >>
operator:
uint32_t t = (uint32_t)(end_time >> 8);
// ^^
// bit-shifting
In the following, the bytes are visualized for a better understanding. If the value end_time
consisted of eight bytes with the symbolic values A B C D E F G H
, what you want is D E F G
:
end_time: A B C D E F G H
end_time >> 8: 0 A B C D E F G
(uint32_t)(end_time >> 8): D E F G
来源:https://stackoverflow.com/questions/23609388/how-to-remove-the-first-3-bytes-and-last-one-byte-from-s64-value