ArrayIndexOutOfBoundsException: Index 256 out of bounds for length 256 in java

-1

I want output an array of integers in java which has a index 5120, but in java only up to 256 index , while in C index to 5120 there is output not 0, I tried changing the loop from <255 to <65536 but instead got an error like the title of this question

Code in C :

    int Tbl0[256],Tbl1[256],Tbl2[256],Tbl3[256];
    int i;
    char SBox={ 0xab,0x88 .....};

unsigned char x, y;

for( i = 0; i < 256; i++ )
{
x = (unsigned char) SBox[i]; 

        y = (x << 1 ^ ((x & 0x80) != 0 ? 0x1B : 0x00));
Tbl0[i] = (int) ( x ^ y ) ^
( (int) x << 8 ) ^
( (int) x << 16 ) ^
( (int) y << 24 );

Tbl0[i] &= 0xFFFFFFFF;

    Tbl1[i] = ( ( ( Tbl0[i] << 24 ) & 0xFFFFFFFF ) | ( ( Tbl0[i] & 0xFFFFFFFF ) >>> 8 ) );





}
        printf("%d\n" , Tbl1[(char)257]);

Output :

1154899012

Java :

    int Tbl0[65536],Tbl1[65536],Tbl2[65536],Tbl3[65536];
        int i;
        char SBox={ 0xab,0x88 .....};
    
    char x;
byte y;
    
    for( i = 0; i < 256; i++ )
    {
    x = (char) SBox[i]; 
    
            y = (byte)(x << 1 ^ ((x & 0x80) != 0 ? 0x1B : 0x00));
    Tbl0[i] = (int) ( x ^ y ) ^
    ( (int) x << 8 ) ^
    ( (int) x << 16 ) ^
    ( (int) y << 24 );
    
    Tbl0[i] &= 0xFFFFFFFF;
    
        Tbl1[i] = ( ( ( Tbl0[i] << 24 ) & 0xFFFFFFFF ) | ( ( Tbl0[i] & 0xFFFFFFFF ) >>> 8 ) );
    
    
    
    
    }

        System.out.println(Tbl1[(char)257]);

Output :

0

I tried to print Tb11 [255] and the results are the same as those in C but after index > 256 the results are always 0, I tried changing the looping to :

for( i = 0; i< 65536; i++)

but I got an error : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 256 out of bounds for length 256

java
c
asked on Stack Overflow Jul 22, 2020 by Atrs • edited Jul 22, 2020 by Atrs

1 Answer

0

A few things.

  • You are only indexing up to 255 in your for loop so there will be nothing in any of the tables at 257.
  • When you change your for loop to 65536 your SBox will throw an exception because it is only of size 256.
  • array indices in Java are integers so why are you casting one to a char?
  • Your tables are not properly declared for Java so everything else is suspect.
answered on Stack Overflow Jul 22, 2020 by WJS • edited Jul 22, 2020 by WJS

User contributions licensed under CC BY-SA 3.0