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.
Related
I m trying to convert 8 bits into one byte. The way the bits are represented are by using a byte object that only contains a 1 or a 0.
If i have a 8 length byte array with these bits, how can i convert them into one byte.
public byte bitsToByte(byte[] bits) {
//Something in here. Each byte inside bits is either a 1 or a 0.
}
Can anyone help?
Thanks
public static byte bitsToByte(byte[] bits){
byte b = 0;
for (int i = 0; i < 8; i++)
b |= (bits[i]&1) << i;
return b;
}
//as an added bonus, the reverse.
public static byte[] bitsToByte(byte bits){
byte[] b = new byte[8];
for (int i = 0; i < 8; i++)
b[i] = (byte) ((bits&(1 << i)) >>> i);
return b;
}
left shift by 1 first for each bit in the array and then add the bit to the byte.
The implementation is based on the assumption that first bit in the array is sign bit and following bits are the magnitude in higher to lower positions of the byte.
public byte bitsToByte(byte[] bits) {
byte value = 0;
for (byte b : bits) {
value <<=1;
value += b;
}
return value;
}
Test the method:
public static void main(String[] args) {
BitsToByte bitsToByte = new BitsToByte();
byte bits[] = new byte[]{0,0,1,0,1,1,0,1}; // 1 + 0 + 4 + 8 + 0 + 32 + 0 + 0
byte value = bitsToByte.bitsToByte(bits);
System.out.println(value);
}
output:
45
Covert the byte array into a byte value (in the same order):
public static byte bitsToByte1(byte[] bits){
byte result = 0;
for (byte i = 0; i < bits.length; i++) {
byte tmp = bits[i];
tmp <<= i; // Perform the left shift by "i" times. "i" position of the bit
result |= tmp; // perform the bit-wise OR
}
return result;
}
input: (same array in reverse)
byte bits1[] = new byte[]{1,0,1,1,0,1,0,0};
value = bitsToByte1(bits1);
System.out.println(value);
output:
45
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);
I have written the following code for 8 bit full adder.While debugging,the control from calling statement in main is going to 'eightbitfullAdderFunction' but it is not evaluating anything in the function. I am getting 00000000 output for addition.Please help me with the code,I have tried making many changes in the logic but of no use.
public class CAModifiedBoothsMultiplier {
public byte[] twosComplement(byte x)
{
byte y= (byte) (~x+1);
byte mask=1;
mask = (byte) (mask << 7);
byte num[] = new byte[10];
byte i=0;
for(i=1;i<=8;i++)
{
if((y & mask)==0)
num[i]=0;
else
num[i]=1;
y=(byte) (y<<1);
}
return num;
}
public byte[] saveByte(byte number)
{
byte mask=1;
mask = (byte) (mask << 7);
byte num[] = new byte[10];
byte i=0;
for(i=1;i<=8;i++)
{
if((number & mask)==0)
num[i]=0;
else
num[i]=1;
number=(byte) (number<<1);
}
return num;
}
public byte[] eightbitFullAdder(byte a,byte b,byte cin)
{
byte sum=0,temp1=0,cout=0;
byte sumno[] = new byte[10];
byte couttemp[]=new byte[10];
couttemp[8]=cin;
byte ain[]=saveByte(a);
byte bin[]=saveByte(b);
for(int i=8;i<=1;i--)
{
temp1= (byte) (ain[i] ^ bin[i]);
sum = (byte) (temp1^couttemp[i]);
sum=(byte) (sum<<7);
sumno[i]=sum;
cout=(byte) ((ain[i] & bin[i]) | (temp1 & couttemp[i]));
if(i!=1)
couttemp[--i]=cout;
}
return sumno;
}
public static void main(String args[])
{
CAModifiedBoothsMultiplier mbm = new CAModifiedBoothsMultiplier();
byte x=5;
byte complementedno[];
complementedno = mbm.twosComplement(x);
for(int i=0;i<=8;i++)
System.out.print(complementedno[i]);
System.out.println("\n");
byte a=2,b=3,cin=0;
byte fulladder[] = mbm.eightbitFullAdder(a,b,cin);
for(int i=0;i<=8;i++)
System.out.print(fulladder[i]);
}
}
In your method "eightbitFullAdder" this line:
for(int i=8;i<=1;i--)
must be
for(int i=8;i>=1;i--)
otherwise, the for-loop is never entered
Could it be that this for loop is checking that int i is less than rather than greater than or equal to 1 while counting down?
"for(int i=8;i<=1;i--)..."
Done the same thing more often than I care to remember, don't worry.
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;
}
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;
}