开发者

Really simple question about creating non-standard sized byte groups

开发者 https://www.devze.com 2023-01-29 21:43 出处:网络
So for a project that space really matters in, I\'d like to be able to write to a file a number which takes up THREE bytes. So essentially, an unsigned type where 16,777,215 is the hig开发者_如何学Che

So for a project that space really matters in, I'd like to be able to write to a file a number which takes up THREE bytes. So essentially, an unsigned type where 16,777,215 is the hig开发者_如何学Chest possible number.

The number is given as an unsigned int, and I've already checked to ensure it's between 0 and 16,777,215. How do I go beyond that?

Code in Java is preferred, but ANSI C works too. Thanks!


You can try

int number = 
OutputStream os =
os.write(number >> 16);
os.write(number >> 8);
os.write(number);

To read

InputStream is = 
int number = ((is.read() & 0xFF) << 16) | ((is.read() & 0xFF) << 8) | (is.read() & 0xFF)

However, given the cost of a byte is so trivial, you have to save an awful lot of them to make the added complexity worth it. I only included it here for your information.

2 TB of disk space is worth about $100
1 GB is worth about 5 cents
1 MB is worth about 0.005 cents
1 KB is worth about 0.000005 cents.
1 B is worth about 0.000000005 cents.

For comparison, at minimum wage, (You may value your time more highly)

1 minute of your time, 12 cents. ~2 GB.
1 second, 0.2 cents. ~40 MB.
1 key, 0.2 seconds, 0.04 cents ~8 MB.
1 blink. 0.05 seconds, 0.01 cents ~2 MB.

This makes the rather disturbing suggestion that its not worth pressing one key to save less that 8 MB. You might even come to the conclusion that its not worth one simple code change unless it saves 2 GB of disk space. :P


In C you could always cast the *int into a *char and then write the 3 least significant bytes. For Big Endian, you skip the first char and write the other three, for little endian, you just write the first three bytes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号