Concatenate bytes to get char - java

How would one concatenate two byte primitives to get one char in java? I'm currently trying this:
byte a = 0x01;
byte b = 0x02;
char c = (char) (a + b);
which gives 0x03. The answer I want is 0x0102.
Is there no simple way to concatenate primitives? I'm surprised there isn't an obvious solution, since it seems like it should be easy. Maybe there is and I just don't see it. :p
Any help would be appreciated.
Thanks!

By shifting left 8 bits and adding. Something like,
byte a = 0x01;
byte b = 0x02;
char c = (char) ((a << 8) + b);
System.out.println(Integer.toHexString(c));
Output is
102
As pointed out in the comments (by #ChrisMartin) you could bitwise-or (and I'll add you might also xor) like
char c = (char) ((a << 8) | b);
and
char c = (char) ((a << 8) ^ b);
To all achieve the same result. Since you should Write Dumb Code I suggest you use whichever you find easiest to understand.

If you are not opposed to using a 3rd party library, Guava's Chars.fromBytes method does exactly this:
char c = Chars.fromBytes(0x01, 0x02);

The correct expression is ((a << 8) | (b & 0xff)):
byte a = (byte) 0x81;
byte b = (byte) 0x82;
char c = (char) ((a << 8) | (b & 0xff));
A byte, when used in an expression, is promoted to an int and when this is done, it is sign-extended. The expressions in the other answer only worked when b <= 127.
If you add 1 more to that value, as a byte, it will have the value -128. (The range of a byte in Java is -128 to 127) so you usually have to mask a byte with b & 0xff when you're using it to store unsigned numbers. You don't need to do that with a in the above expression since all the high-order bits are shifted out of the resulting 16-bit char.

Related

JAVA Byte Manipulation

I want to read a binary file and do some manipulation on each byte. I want to test that I am manipulating the bytes correctly. I want to set a byte variable1 to "00000000" and then another byte variable2 set at "00001111" and OR them newvariable = variable1|variable2, shift the newvariable << 4 bits and then print out the int value.
byte a = 00000000;
//Convert first oneByte to 4 bits and then xor with a;
byte b = 00001111;
byte c = (byte)(a|b);
c = c << 4;
System.out.println("byte= " + c + "\n");
I am not sure why I keep getting "incompatiable types:possible lossy conversion from byte to int"
You need to put a '0b' in front of those numbers to express binary constants. The number 00001111 is interpreted as a literal in octal, which is 585 in decimal. The max byte is 127 (since it's signed). Try 0b00001111 instead.
As literals, those will still be int, so depending on where you do the assignment, you may also need to explicitly cast down to byte.

Int to byte array - byte shifting

I'm trying to convert an int (max. 65535) to an two bytes array.
In C I used an uint16, but Java doesn't know any unsigned values.
To convert the bytes to an array I tried to use this:
byte[] data = { (byte) ((num >> 8) & 0xff), (byte) (num & 0xff) };
But I only get: [63, -49] instead of: [63, 207], if I use 16335 as value.
Is there a way to do this in Java?
I need this unsigned byte in an byte array to send it using an outputstream
You can use java's NIO's ByteBuffer for the purpose:
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.println(Byte.toUnsignedInt(b));
}
Hope now it would work ;)

Java syntax - extra plus sign after cast is valid?

So I came across something that confused me when casting a byte to char, usually I would do this:
for (byte b:"ABCDE".getBytes()) {
System.out.println((char)b);
}
Which will print out
A
B
C
D
E
I accidentally left a + between the (char) and b and got the same result!?
Like so:
for (byte b:"ABCDE".getBytes()) {
System.out.println((char) + b);
}
Why exactly is this happening?
Am I essentially doing (char)(0x00 + b)? Because
System.out.println((char) - b);
yields a different result.
Note: Using Java version 1.8.0_20
Why exactly is this happening?
If you put a unary - operator before a number or expression it negates it.
Similarly, if you put a unary + operator before a number or expression it does nothing.
A safer way to convert a byte to a char is
char ch = (char)(b & 0xFF);
This will work for characters between 0 and 255, rather than 0 to 127.
BTW you can use unary operators to write some confusing code like
int i = (int) + (long) - (char) + (byte) 1; // i = -1;
b is a byte, and that be expressed as + b as well. For example, 3 can be written as +3 as well. So, ((char) + b) is same as ((char) b)
The + is the unary plus operator - like you can say that 1 is equivalent to +1, b is equivalent to +b. The space between + and b is inconsequential. This operator has a higher precedence than the cast, so after it's applied (doing nothing, as noted), the resulting byte is then cast to a char and produces the same result as before.

What does & 0xff do And MD5 Structure?

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class JavaMD5 {
public static void main(String[] args) {
String passwordToHash = "MyPassword123";
String generatedPassword = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(passwordToHash.getBytes());
byte[] bytes = md.digest();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
generatedPassword = sb.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(generatedPassword);
}
}
This line is the problem :
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
what does each part do in this structure????
Thanks and I'm sorry for asking Beacuse I'm new in java.
Presumably most of the code is clear and the only mystery for you here is this expression:
(bytes[i] & 0xff) + 0x100
The first part:
bytes[i] & 0xff
widens the byte at position i to an int value with zeros in bit positions 8-31. In Java, the byte data type is a signed integer value, so the widening sign-extends the value. Without the & 0xff, values greater than 0x7f would end up as negative int values. The rest is then fairly obvious: it adds 0x100, which simply turns on the bit at index 8 (since it is guaranteed to be 0 in (bytes[i] & 0xff). It is then converted to a hex String value by the call to Integer.toString(..., 16).
The reason for first adding 0x100 and then stripping off the 1 (done by the substring(1) call, which takes the substring starting at position 1 through the end) is to guarantee two hex digits in the end result. Otherwise, byte values below 0x10 would end up as one-character strings when converted to hex.
It's debatable whether all that has better performance (it certainly isn't clearer) than:
sb.append(String.format("%02x", bytes[i]));
It's a really messy way of translating to a hexadecimal string.
& 0xFF performs a binary AND, causing the returning value to be between 0 and 255 (which a byte always is anyway)
+ 0x100 adds 256 to the result to ensure the result is always 3 digits
Integer.toString(src, 16) converts the integer to a string with helix 16 (hexadecimal)
Finally .substring(1) strips the first character (the 1 from step 2)
So, this is a very elaborate and obfuscated way to convert a byte to an always 2-character hexadecimal string.

I want to convert byte data in Java to C

I want to convert byte data in Java to byte in C.
a is int and b is byte; and I have code in Java like this:
b[0x00] = (byte) ((a>> 8) & 0xFF);
how can I convert above statement in C?
Actually this is virtually equivalent in C as both the >> and & operators are identical in both languages.
int a=2200;
unsigned char b=((a>>8) & 0xFF);

Categories