简体   繁体   中英

how to cast int [] data type to byte [] data type

I have the following error in compiler

return  ans;
                ^
  required: byte[]
  found:    int[]

I have this method in which i want to return a type of byte . Can anyone tell me how can i cast ans to make it compatible with me method type

public  byte[]  element(int m) {
    //if (q!= a.length)
    // throw new Exception("Array length does not equal k");
    int f;
    int q;
    int[] t;

    this.first = f;
    this.second = q;
    this.data = new int[q];

    for (int i = 0; i < t.length; ++i) {
        this.data[i] = t[i];
    }

    // if (!this.IsValid())
    //  throw new Exception("Bad value from array");


    int ans[] = new int[this.second];

    int a = this.first;
    int b = this.second;
    int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m

    for (int i = 0; i < this.second; ++i) {
        ans[i] = largestV(a, b, x); // largest value v, where v < a and vCb < x
        x = x - choose(ans[i], b);
        a = ans[i];
        b = b - 1;
    }

    for (int i = 0; i < this.second; ++i) { 
        ans[i] = (first-1) - ans[i];
        return  ans;
    }
}

Note: i want it to return type of byte not int but i am trying to cast ans but without success .

You have to change int[] ans to Byte[] ans, you are trying to return an int array, but you have to return your byte array

int f;
   int q;
  int [] t;

    this.first = f;
    this.second = q;
    this.data = new int[q];
    for (int i = 0; i < t.length; ++i)
      this.data[i] = t[i];

   // if (!this.IsValid())
    //  throw new Exception("Bad value from array");


        byte ans []= new byte[this.second];

        int a = this.first;
        int b = this.second;
        int x = (choose(this.first,this.second) - 1) - m; // x is the "dual" of m

        for (int i = 0; i < this.second; ++i) {
            ans[i]= largestV(a, b, x); // largest value v, where v < a and vCb < x
            x = x - choose(ans[i], b);
            a = ans[i];
            b = b - 1;
        }

        for (int i = 0; i < this.second; ++i)

            ans[i] = (first-1) - ans[i];

        return  ans;
    }

Dunno why you would wanna to work on int and return a byte . Dat aside, You can create a new byte array of the same size as ans and do this in the last loop

for (int i = 0; i < this.second; ++i)
{ 
    ans[i] = (first-1) - ans[i]);
    ans_byte_version[i] =  (byte) ((first-1) - ans[i]);
}
return ans_byte_version;

However it'd be better if you tell us what are you trying to do. Why have you declared int when you want byte in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM