java将文件读成byte,如何在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.

Can this be done in Java, and if yes, how?

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.

解决方案

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.

EDIT: 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

Do all your arithmetic using int, and then cast back to byte when you need to write it out again.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值