string to byte then byte[] 0xformat - java

I am having problems of conversion through string->byte->byte[]
What I have done so far:
double db = 1.00;
double ab = db*100;
int k = (int) ab;
String aa = String.format("%06d", k);
String first = aa.substring(0,2);``
String second = aa.substring(2,4);
String third = aa.substring(4,6);
String ff = "0x"+first;
String nn = "0x"+second;
String yy = "0x"+third;
I want to write those bytes to an byte[]. What I mean is:
byte[] bytes = new byte[]{(byte) 0x02, (byte) 0x68, (byte) 0x14,
(byte) 0x93, (byte) 0x01, ff,nn,yy};
in this order and casted with 0x's. Any help is greatly appriciated.
Regards,
Ali

You can use Byte.decode()
Decodes a String into a Byte. Accepts decimal, hexadecimal, and octal numbers given by the following grammar:
DecodableString:
Signopt DecimalNumeral
Signopt 0x HexDigits
Signopt 0X HexDigits
Signopt # HexDigits
Signopt 0 OctalDigits
Below code will print 10, 11 which is value of 0XA, 0XB
byte[] temp = new byte[2];
temp[0] = Byte.decode("0xA");
temp[1] = Byte.decode("0xB");
System.out.println(temp[0]);
System.out.println(temp[1]);

As I see, the main question here is how to convert a 2 char String representing a hexa number to a byte type. The Byte class has a static method parseByte(String s, int radix) that can parse a String to number using the radix you want (in this case, 16). Here is an example of how you can do the parsing and save the result in a byte array:
public static void main(String [] args){
System.out.println(Arrays.toString(getBytes("0001020F")));
}
public static byte[] getBytes(String str) {
byte [] result = new byte[str.length() / 2]; //assuming str has even number of chars...
for(int i = 0; i < result.length; i++){
int startIndex = i * 2;
result[i] = Byte.parseByte(str.substring(startIndex, startIndex + 2), 16);
}
return result;
}

Related

Java - SNMP - Converting OctetString to Float

currently I am playing around with SNMP (snmp4j and SimpleSnmpClient) to get some information from a network device.
This works as long as the result is a "normal" value like an integer.
If the value is an OctetString like
44:00:4f:00:30:00:4a:00:47:00:20:00:4d:00:49:00:58:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
labelled as Unicode I can decode it as well but before I have to replace the ":"
hex2AscII(sysDescr.replace(":", "")
with this method
static String hex2AscII(String hex) {
StringBuilder ascii = new StringBuilder();
for (int i = 0; i < hex.length(); i+=2) {
String str = hex.substring(i, i+2);
ascii.append((char)Integer.parseInt(str, 16));
}
return ascii.toString();
}
Now I want to get the value for a Voltage, the MiB says
OCTECT STRING (SIZE(4))
It should be changed to float format
OK I do the SNMP query and get as result:
e6:d9:4c:41
witch should be a voltage around 12.8 Volt
Now I try to convert it to Float
System.out.println("################# TestSection ################# ");
int hex = 0xE6D94C41;
f = Float.intBitsToFloat(hex);
System.out.println(f);
System.out.printf("%f", f);
and get
-5.1308008E23
e6d94c41
So what is wrong with my code ?
Here is the proper way of doing it in Java:
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class SnmpUtil{
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
public static void main(String []args){
byte[] bytes = SnmpUtil.hexStringToByteArray("e6d94c41");
float f = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
System.out.println(f);
}
}

Java Byte Operation - Converting 3 Byte To Integer Data

I have some byte-int operations. But I cant figure out the problem.
First of all I have a hex data and I am holding it as an integer
public static final int hexData = 0xDFC10A;
And I am converting it to byte array with this function:
public static byte[] hexToByteArray(int hexNum)
{
ArrayList<Byte> byteBuffer = new ArrayList<>();
while (true)
{
byteBuffer.add(0, (byte) (hexNum % 256));
hexNum = hexNum / 256;
if (hexNum == 0) break;
}
byte[] data = new byte[byteBuffer.size()];
for (int i=0;i<byteBuffer.size();i++){
data[i] = byteBuffer.get(i).byteValue();
}
return data;
}
And I want to convert 3 byte array to integer back again how can I do that?
Or you can also suggest other converting functions like hex-to-3-bytes-array and 3-bytes-to-int thank you again.
UPDATE
In c# someone use below function but not working in java
public static int byte3ToInt(byte[] byte3){
int res = 0;
for (int i = 0; i < 3; i++)
{
res += res * 0xFF + byte3[i];
if (byte3[i] < 0x7F)
{
break;
}
}
return res;
}
This will give you the value:
(byte3[0] & 0xff) << 16 | (byte3[1] & 0xff) << 8 | (byte3[2] & 0xff)
This assumes, the byte array is 3 bytes long. If you need to convert also shorter arrays you can use a loop.
The conversion in the other direction (int to bytes) can be written with logical operations like this:
byte3[0] = (byte)(hexData >> 16);
byte3[1] = (byte)(hexData >> 8);
byte3[2] = (byte)(hexData);
You could use Java NIO's ByteBuffer:
byte[] bytes = ByteBuffer.allocate(4).putInt(hexNum).array();
And the other way round is possible too. Have a look at this.
As an example:
final byte[] array = new byte[] { 0x00, (byte) 0xdf, (byte) 0xc1, 0x0a };//you need 4 bytes to get an integer (padding with a 0 byte)
final int x = ByteBuffer.wrap(array).getInt();
// x contains the int 0x00dfc10a
If you want to do it similar to the C# code:
public static int byte3ToInt(final byte[] byte3) {
int res = 0;
for (int i = 0; i < 3; i++)
{
res *= 256;
if (byte3[i] < 0)
{
res += 256 + byte3[i]; //signed to unsigned conversion
} else
{
res += byte3[i];
}
}
return res;
}
to convert Integer to hex: integer.toHexString()
to convert hexString to Integer: Integer.parseInt("FF", 16);

How to convert minus hex value to String and byte array

I want to convert decimal -10 value to hex in a String and byte array format.
I have tried
String minHex = Integer.toHexString(Integer.valueOf(-10));
System.out.println(minHex);
Which results in fffffff6, and I think it is not correct. And for converting byte array I am using below function which I found from
Convert a string representation of a hex dump to a byte array using Java?
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
So also not sure it will work for minus hex value or not.
To convert an hex to a String the way you expect it i.e. -10 is converted to -a, use:
String hex = Integer.toString(-10, 16);
To convert to a byte array, simply convert the int to a byte array, it is represented the same way:
byte[] bytes = ByteBuffer.allocate(4).putInt(-10).array();

Checksum Calculation - two's complement of the least significant byte

I'm attempting to create a check sum by calculating the two's complement of the least significant byte of the sum of all the data bytes in an array.
So given an array:
byte[] bytes = new byte[] { 0x01, 0x02 };
would something like this work...
public static void main(String []args)
{
byte[] bytes = new byte[] { 0x01, 0x02 };
BigInteger bi = new BigInteger(bytes);
BigInteger biRes = bi.not().add(BigInteger.ONE);
byte[] result = biRes.toByteArray();
System.out.println("a: " + result);
System.out.println("b: " + javax.xml.bind.DatatypeConverter.printHexBinary(result));
}
Produces...
a: [B#34bdb859
b: FEFE
Is this correct?
I have another solution :
private static byte calculateChecksum8(byte[] bytes){
byte result = 0;
for(int i = 0; i < bytes.length; i++){
result += bytes[i];
}
result = (byte) (~ result & 0xFF);
result = (byte) (result +1 & 0xFF);
String str = String.format("%02x", result);
System.out.println(result+" = "+str.toUpperCase());
return result;
}
Someone to confirm ?
Just add up all the bytes, negate the resuit, cast or truncate it to a byte, and you're done.

Convert byte-array to a bit byte-array

Hello stackoverflow community,
I need to convert a byte array to a binary byte-array (yes, binary bytes). See this example:
byte[] source = new byte[] {0x0A, 0x00};
//shall be converted to this:
byte[] target = new byte[] {0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00};
//this would be ok as well:
also[0] = new byte[] {0x00, 0x00, 0x10, 0x10};
also[1] = new byte[] {0x00, 0x00, 0x00, 0x00};
At the moment I'm solving this by using Integer.toBinaryString to get the binary string and hexStringToByteArray to convert the binary string to a byte array:
for(int o = 0; o < cPage.getCpData().length; o+=cPage.getWidth()) {
String fBinString = "";
for(int u = 0; u < cPage.getWidth(); u++) {
byte[] value = new byte[1];
raBa.read(value);
Byte part = new BigInteger(value).byteValue();
String binString = Integer.toBinaryString(0xFF & part);
fBinString+=("00000000" + binString).substring(binString.length());
}
cPage.addBinaryString(fBinString);
//binaryCodepage.add(fBinString);
testwidth = fBinString.length();
//System.out.println(fBinString);
}
//other class:
public byte[][] getBinaryAsByteArray() {
Object[] binary = getBinaryStrings().toArray();
byte[][] binAsHex = new byte[binary.length][getWidth()*8];
for(int i = 0; i < binary.length; i++) {
binAsHex[i] = ByteUtil.hexStringToByteArray(((String) binary[i]));
}
return binAsHex;
}
This works fine for small source byte-arrays but takes ages for large byte-arrays. Thats probably caused by the conversion to binary String and back.
Any ideas how to improve this by not converting the source to a String?
I don't know what's the motivation to this strange conversion, but you could do something similar to the implementation of Integer.toBinaryString :
private static byte[] toFourBytes(byte i) {
byte[] buf = new byte[4];
int bytePos = 4;
do {
buf[--bytePos] = i & 0x3;
i >>>= 2;
} while (i != 0);
return buf;
}
This should convert (I haven't tested it) each byte to a 4 byte array, in which each byte contains 2 bits of the original byte.
EDIT:
I may have missed the exact requirement. If the two bits extracted from the input byte should be in positions 0 and 4 of the output byte, the code would change to :
private static byte[] toFourBytes(byte i) {
byte[] buf = new byte[4];
int bytePos = 4;
do {
byte temp = i & 0x1;
i >>>= 1;
buf[--bytePos] = ((i & 0x1) << 4) | temp;
i >>>= 1;
} while (i != 0);
return buf;
}

Categories

Resources