TLDR: Java is signed, c# is unsigned. Byte[]
values are different, how to solve this. How can I convert either side to the other?
Values are of "Hello World"
MD5
hashed and then converted to bytes
Java:
-79, 10, -115, -79, 100, -32, 117, 65, 5, -73, -87, -101, -25, 46, 63, -27
C#:
177, 10, 141, 177, 100, 224, 117, 65, 5, 183, 169, 155, 231, 46, 63, 229
I use the byte[]
to encrypt using AES
on both sides but the passwords never match.
equals(byte[] a, byte[] a2) method returns true if the two specified arrays of bytes are equal to one another. Two arrays are equal if they contain the same elements in the same order.
In C#, byte is the data type for 8-bit unsigned integers, so a byte[] should be an array of integers who are between 0 and 255, just like an char[] is an array of characters.
A byte is a group of 8 bits. A bit is the most basic unit and can be either 1 or 0. A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.
The bytes have identical values, they are just printed differently.
If you would like to ensure that bytes with negative values are displayed as positive numbers, add 256 and take modulo 256, like this:
for (byte b : byteArray) {
int n = (b + 256) % 256;
System.out.println(n);
}
Similarly, if you would like to bring your values above 128 into the proper range of byte, you can cast them to truncate the upper bytes and get negative values, or if you prefer you could subtract 256:
for (int n : byteValuesAsInt) {
byte b1 = (byte)n;
byte b2 = n >= 128 ? n-256 : n;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With