Binary Int Array to ASCII Equivalent in Java - java

I searched around here for awhile and nothing seems to help me with my assignment. I'm trying to convert an int array that has binary code in it manually, do the decimal conversion and then cast it as a char to get the ascii equivalent. I have something started, but when I print it out, I get -591207182 as the message, which obviously isn't correct. I have my program down below. I'm fairly novice at writing and understanding Java, so the most efficient and easy to understand route would be much appreciated.
class DecodeMessage
{
public void getBinary(Picture secretImage)
{
Pixel pixelObject = null;
Color pixelColor = null;
int [] binaryInt = new int[secretImage.getWidth()];
int x = 0;
int redValue = 0;
while(redValue < 2)
{
Pixel pixelTarget = new Pixel(secretImage,x,0);
pixelColor = pixelTarget.getColor();
redValue = pixelColor.getRed();
binaryInt[x] = redValue;
x++;
}
}
public void decodeBinary(int [] binary)
{
int binaryLen = binary.length;
long totVal = 0;
int newVal = 0;
int bitVal = 0;
long preVal = 0;
long base = 2;
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
preVal = bitVal * base;
totVal += preVal;
base = base * 2;
}
System.out.println(totVal);
}
}
public class DecodeMessageTester
{
public static void main(String[] args)
{
Picture pictureObj = new Picture("SecretMessage.bmp");
pictureObj.explore();
DecodeMessage decode = new DecodeMessage();
decode.getBinary(pictureObj);
int[] bitArray = {0,1,1,0,0,0,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1};
decode.decodeBinary(bitArray);
}
}

Your problem is that you're trying to squeeze all 48 bits into one int. However, as http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html states, an int in Java can only hold 32 bits, so your numbers overflow. Try changing base, preVal and totVal to long, which can hold 64 bits.
Of course, if you need more than 64 bits (or 63 actually because the last bit is the sign bit), you will not be able to use a primitive number datatype to hold that.

Related

Bitwise representation into a byte array function

I'm trying to do a memory writing program with bits as part of a CPU simulating program and I don't understand something. I'm making a function to write int value into the memory which is byte double array broken down into segments. Now, I don't understand why the following writeWord function is not working probably, I'll post relevant code as well as the function.
public class RealMemory implements Memory {
public static final int BYTES_PER_INT = 4;
public static final int BITS_PER_BYTE = 8;
private final int segmentSize;
private final int numberOfSegments;
private byte[][] memory;
public RealMemory (int segmentSize, int numberOfSegments) {
this.segmentSize = segmentSize;
this.numberOfSegments = numberOfSegments;
this.memory = new byte[this.numberOfSegments][this.segmentSize];
}
private byte[] getSegment(int segment) {
assert(segment >= 0 && segment < numberOfSegments);
return memory[segment];
}
public void writeWord (int segment, int offset, int value) {
assert (offset >= 0 && offset < segmentSize - BYTES_PER_INT
&& offset % BYTES_PER_INT == 0);
byte[] byteword = new byte[BYTES_PER_INT];
int mask = 1;
for (int i=offset; i < offset + BYTES_PER_INT; i++) {
byteword[i-offset] = (byte) (value & mask);
mask <<= 1;
getSegment(segment)[i]=byteword[i-offset];
}
}
}
I know the way I try to breakdown the value into bits is wrong, I just don't understand bitwise operation needed here fully is my guess. Any help?
Your problem is mask = 1. You don't read bytes, but single bits instead.
To read bytes, use int mask = (1 << BITS_PER_BYTE) - 1; and mask <<= BITS_PER_BYTE;. Once you masked out the relevant parts you also have to shift it to the right. As Stanislav Bashkyrtsev suggested, this can be done directly on the value instead of shifting the mask.
int mask = (1 << BITS_PER_BYTE) - 1;
for (int i=offset; i < offset + BYTES_PER_INT; i++) {
byteword[i-offset] = (byte) (value & mask);
value >>= BITS_PER_BYTE;
getSegment(segment)[i]=byteword[i-offset];
}

How to manipulate the bits in a long?

I want to transform a long to binary code, then change some bits and get the long again. I have found this post Java long to binary but I still can't achieve what I want.
I think there is two ways to achieve my goal:
Going from long to bitset and to long again
Going from long to binary String and then to int array and then to long again
public static long changeHalf(long x){
int[] firstHalf = new int[32];
int[] secondHalf = new int[32];
int[] result = new int[64];
String binaryOfLong = Long.toBinaryString(x);
for (int i = 0; i < firstHalf.length; i++) {
}
for (int i = 0; i < secondHalf.length; i++) {
result[i] = secondHalf[i];
}
for (int i = 0; i < firstHalf.length; i++) {
result[i+32] = firstHalf[i];
}
String s = Arrays.toString(result);
return Long.parseLong(s);
}
Rather than converting a long to arrays of int, just use bitwise operations.
I want to swap the first 32 bits with the last 32 bits
That would be:
long result = ((x & 0xFFFFFFFF00000000l) >> 32) | ((x & 0x00000000FFFFFFFFl) << 32);
That masks off the first 32 bits, shifts them to the right, masks off the last 32 bits, shifts them to the left, and combines the result with | (OR).
Live example:
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
long x = 0x1000000020000000l;
long result = ((x & 0xFFFFFFFF00000000l) >> 32) | ((x & 0x00000000FFFFFFFFl) << 32);
System.out.printf("0x%016X\n", x);
System.out.printf("0x%016X\n", result);
}
}
Outputs:
0x1000000020000000
0x2000000010000000
More in the Bitwise and Bit Shift Operators tutorial.

Get X-Coordinate of Elliptical Curve using Bouncy Castle

I tried to calculate Tr(x) operation for x coordinate of the elliptical curve F2m (m = 163). For that, I used "Bouncy Castle" with corresponding types. Trace for my elliptical curve is equal to either 0 or 1 and my code is the following:
public int CalculateTrace_Test(byte[] array)
{
int m = 163;
BigInteger two = new BigInteger("2", 10);
BigInteger x = new BigInteger(array);
BigInteger xi = x;
BigInteger temp = x;
for (int i = 1; i < m; i++)
{
var next = xi.ModPow(two.Pow(i), fx);
temp = temp.Xor(next);
}
return temp.IntValue;
}
Here fx is an integer formed from the irreducible polynomial f(x) = x^163+x^7+x^6+x^3 + 1.
So my problem that it doesn't work and as result, I have everything but not 1 or 0. Could anyone please tell me what is wrong in my implementation of the trace?
It doesn't look like you are properly doing field arithmetic in GF(2m). The classes that support correct field arithmetic are in the package org.bouncycastle.math.ec. Take a look at ECFieldElement.F2m and ECCurve.F2m. Also, for your specific case which corresponds to the SECT163 reduction polynomial, the class SecT163FieldElement may be particularly useful.
Here some code copied directly from the class org.bouncycastle.math.ec.tools.TraceOptimizer. The code assumes the the finite field is of characteristic 2.
private static int calculateTrace(ECFieldElement fe) {
int m = fe.getFieldSize();
ECFieldElement tr = fe;
for (int i = 1; i < m; ++i) {
fe = fe.square();
tr = tr.add(fe);
}
BigInteger b = tr.toBigInteger();
if (b.bitLength() > 1) {
throw new IllegalStateException();
}
return b.intValue();

Large Powers without using Big Integer

I had a problem where i had to calculate sum of large powers of numbers in an array and return the result.For example arr=[10,12,34,56] then output should be
10^1+12^2+34^3+56^4.Here the output could be very large so we were asked to take a mod of 10^10+11 on the output and then return it.I did it easily in python but in java initially i used BigInteger and got tle for half the test cases so i thought of using Long and then calculating power using modular exponential but then i got the wrong output to be precise all in negative as it obviously exceeded the limit.
Here is my code using Long and Modular exponential.
static long power(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1)==1)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
static long solve(int[] a) {
// Write your code here
Long[] arr = new Long[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = setBits(new Long(a[i]));
}
Long Mod = new Long("10000000011");
Long c = new Long(0);
for (int i = 0; i < arr.length; i++) {
c += power(arr[i], new Long(i + 1),Mod) % Mod;
}
return c % Mod;
}
static long setBits(Long a) {
Long count = new Long(0);
while (a > 0) {
a &= (a - 1);
count++;
}
return count;
}
Then i also tried Binary Exponentiation but nothing worked for me.How do i achieve this without using big integer and as easily as i got it in python
You have added an extra zero the value of mod, it should be 1000000011.
Hope this will solve it

How to convert a binary value to ASCII in JAVA?

This is a homework assignment that I can't wrap my head around. I have to do it manually, so I can't use "getBytes()." Also, I have to convert to decimal format first, and then convert the decimal to ASCII (e.g. {0,1,1,0,0,0,1,0} = 98 in decimal format, which is a 'b'). I have arranged the binary code into an array, and want to use a for loop to traverse the array position by position. However, I'm not sure I'm using the correct parameters for the for loop, and am not sure how to divide the code into bits of "8." Another thing, how to I convert the decimal value to ASCII? Should I just list out all the possible letters I know I will get, and then refer to them using an if-else loop? Or could I just convert the decimal to a char? Here is my code so far... (It's a bit messy, sorry)
class Decoder
{
public void findCode(Picture stegoObj)
{
Pixel pixTar = new Pixel(stegoObj,0,0);
Pixel [] pixelArray = stegoObj.getPixels();
int blueVal = 0;
for(int length = 0; length < pixelArray.length; length++)
{
blueVal = pixTar.getBlue();
}
System.out.println(blueVal);
stegoObj.explore();
}
public void decode(int [] binary)
{
int binaryLen = binary.length;
int totVal = 0;
int newVal = 0;
int bitVal = 0;
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
int exp = x - (binaryLen - 1);
totVal += (pow(bitVal, exp));
}
System.out.println(totVal);
}
}
public class DecodeImage
{
public static void main(String[] args)
{
Picture stegoObj = new Picture("SecretMessage.bmp");
Decoder deco = new Decoder();
int[] binArray = {0,1,0,1,0,1,0,0,0,1,1,0,1,0,0,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,0,0,0,1,1,1,0,1,1,1,0,1,1,0,1,1,1,1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,0,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,1,0,1,0,0,0,0,1,1,0,1,0,0,0,0,1,0,1,0};
//int[] binArray = {0,1,1,0,0,0,1,0};
//deco.findCode(stegoObj);
deco.decode(binArray);
}
}
EDIT:
Okay, so I figured out this much, under the class Decoder, in the decode block, in the for loop:
for(int x = binaryLen - 1; x >= 0; x--)
{
bitVal = binary[x];
preVal = bitVal * base;
totVal += preVal;
base = base * 2;
}
You've got the right idea for decode. I don't see why your code wouldn't work, although I don't see the pow implementation anywhere.
Decimal to ascii is easy, just cast the value to a char:
int v = ...; // decimal value
char c = (char)v; // ascii value
int[] bValue = {1,0,0,0,1,0,1};
int iValue = 0;
// convert binary to decimal
for (int i = 0, pow = bValue.length - 1 ; i < bValue.length ; i++, pow--)
iValue += bValue[i]*Math.pow(2, pow);
// gets the value as a char
char cValue = (char)iValue;
System.out.println("Int value: "+iValue +", Char value : "+cValue);
If you need the whole ASCII table, you may put the values into a Map where the key is the integer value, and the value is the corresponding ASCII entry.

Categories

Resources