如何在Java中将文件读取为无符号字节? [英] How can I read a file as unsigned bytes in Java?
问题描述
如何用Java将文件读取为字节?
How can I read a file to bytes in Java?
请注意,所有字节都必须为正,即不能使用负范围,这一点很重要。
It is important to note that all the bytes need to be positive, i.e. the negative range cannot be used.
这可以用Java完成吗,如果可以,怎么办?
Can this be done in Java, and if yes, how?
我需要能够将文件的内容乘以一个常数。我以为我可以将字节读到BigInteger中,然后相乘,但是由于某些字节是负数,所以我最终得到12 13 15 -12等并被卡住。
I need to be able to multiply the contents of a file by a constant. I was assuming that I can read the bytes into a BigInteger and then multiply, however since some of the bytes are negative I am ending up with 12 13 15 -12 etc and get stuck.
推荐答案
好吧,Java没有无符号字节的概念... byte
类型始终是带符号的,值从-128到127(含)。但是,这将与其他使用无符号值的系统很好地互操作,例如,写入字节 255的C#代码将生成一个文件,该文件在Java中将相同的值读取为 -1。
Well, Java doesn't have the concept of unsigned bytes... the byte
type is always signed, with values from -128 to 127 inclusive. However, this will interoperate just fine with other systems which have worked with unsigned values for example, C# code writing a byte of "255" will produce a file where the same value is read as "-1" in Java. Just be careful, and you'll be okay.
编辑:您可以将带符号的字节转换为 int
使用位掩码非常容易地使用 unsigned 值。例如:
You can convert the signed byte to an int
with the unsigned value very easily using a bitmask. For example:
byte b = -1; // Imagine this was read from the file
int i = b & 0xff;
System.out.println(i); // 255
使用 int
,然后在需要再次写回 byte
时回退。
Do all your arithmetic using int
, and then cast back to byte
when you need to write it out again.
通常读取二进制数据从使用 FileInputStream
或 FileChannel
。
You generally read binary data from from files using FileInputStream
or possibly FileChannel
.
现在很难知道您还在寻找什么。 。如果您可以在问题中提供更多详细信息,我们也许可以为您提供更多帮助。
It's hard to know what else you're looking for at the moment... if you can give more details in your question, we may be able to help you more.
这篇关于如何在Java中将文件读取为无符号字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!