简体   繁体   中英

Equivalent in Java

Taking me hours already to figure this out by googling and I think need help here. I have a snippet that is causing it not to work like its equivalent in objective c so would need some experts' help.

What are the equivalent of the objective c snippets below in java?

unsigned char mByte[CC_SHA1_DIGEST_LENGTH];

uint64_t tBytes = 0xFFFFFFFF;

Well there is no absolute equivalent, if all languages were the same why would we need more than one?

The closest thing is probably:

final int CC_SHA1_DIGEST_LENGTH = 1024; //some length
char[] mByte = new char[CC_SHAR1_DIGEST_LENGTH];

//there is no unsigned keyword in java
//The long data type is a 64-bit two's complement integer
long tBytes = Long.MAX_VALUE;

long tBytes=0xFFFFFFFF; would also work, but this is a negative number (because it is treated as an integer, not a long). If you want it to be long you need to add L ( 0xFFFFFFFFL ) at the end. Be careful! More info on the primitive datatypes can be found here .

unsigned char mByte[CC_SHA1_DIGEST_LENGTH]; equivalent in java will be

final int CC_SHA1_DIGEST_LENGTH=1024;

byte mByte[CC_SHA1_DIGEST_LENGTH];

though mByte is unsigned so when you work with mByte array you have to convert byte value to unsigned using 0xFF. for example, mByte[0]=(0x88 & 0xFF);

uint64_t tBytes = 0xFFFFFFFF; equivalent in java will be

long tBytes = 0xFFFFFFFF;

Well the rule of thumb would be to match type lenght's in bits.
In C unsigned char is 8 bit wide, so Java equivalent would be byte .
In C uint64_t is 64 bit wide, so Java equivalent would be long .
So therefore Java equivalent would be:

//SHA1 lenght would be 20 bytes
public static final int CC_SHA1_DIGEST_LENGTH = 20;
byte mBytes[] = new byte[CC_SHA1_DIGEST_LENGTH];
long tBytes = 0xFFFFFFFF;

@user3200809 mByte[0]=(0x88 & 0xFF); - this operation is pointless unless you have value larger than 8 bits.
See the same operation in binary:

 1000 1000
&
 1111 1111
=
 1000 1000

When assigning to mByte[i] you would have to type cast to byte anyway so all excessive bits will be chopped.

When we look at memory representation of those types there is no difference between signed and unsigned types.

I'm guessing from authors post that he works with SHA1 algorithm which is bunch of binary operations (xor's, and's, shift's).
So for binary operations there is no difference that type is signed or unsigned:

byte b = (byte) 0x80; //-128 in signed decimal
b ^= (byte) 0x01;
System.out.printf("0x%x", b); // prints 0x81 which is -127 in signed decimal

BUT you could run into problems if you're doing eg division.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM