5 * Created by Christian Brunschen on 05/05/2008.
6 * Copyright 2008 Google UK. All rights reserved.
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
25 #include "GF256Poly.h"
26 #include "../IllegalArgumentException.h"
28 #include "../Counted.h"
30 using namespace common;
32 namespace reedsolomon {
33 static inline ArrayRef<int> makeArray(int value) {
34 ArrayRef<int> valuesRef(new Array<int>(value, 1));
38 static inline Ref<GF256Poly> refPoly(GF256 &field, int value) {
39 ArrayRef<int> values(makeArray(value));
40 Ref<GF256Poly> result(new GF256Poly(field, values));
44 GF256::GF256(int primitive) :
45 exp_((const int)0, 256),
46 log_((const int)0, 256),
47 zero_(refPoly(*this, 0)),
48 one_(refPoly(*this, 1)) {
50 for (int i = 0; i < 256; i++) {
57 // log(0) == 0, but should never be used
59 for (int i = 0; i < 255; i++) {
65 Ref<GF256Poly> GF256::getZero() {
69 Ref<GF256Poly> GF256::getOne() {
73 Ref<GF256Poly> GF256::buildMonomial(int degree, int coefficient) {
75 cout << __FUNCTION__ << "\n";
78 throw new IllegalArgumentException("Degree must be non-negative");
80 if (coefficient == 0) {
83 int nCoefficients = degree + 1;
84 ArrayRef<int> coefficients(new Array<int>(nCoefficients));
85 coefficients[0] = coefficient;
86 Ref<GF256Poly> result(new GF256Poly(*this, coefficients));
90 int GF256::addOrSubtract(int a, int b) {
94 int GF256::exp(int a) {
98 int GF256::log(int a) {
100 throw new IllegalArgumentException("Cannot take the logarithm of 0");
105 int GF256::inverse(int a) {
107 throw new IllegalArgumentException("Cannot calculate the inverse of 0");
109 return exp_[255 - log_[a]];
112 int GF256::multiply(int a, int b) {
113 if (a == 0 || b == 0) {
122 return exp_[(log_[a] + log_[b]) % 255];
125 GF256 GF256::QR_CODE_FIELD(0x011D); // x^8 + x^4 + x^3 + x^2 + 1
126 GF256 GF256::DATA_MATRIX_FIELD(0x012D); // x^8 + x^5 + x^3 + x^2 + 1
128 ostream& operator<<(ostream& out, const GF256& field)
130 out << "Field[\nexp=(";
131 out << field.exp_[0];
132 for (int i = 1; i < 256; i++) {
133 out << "," << field.exp_[i];
136 out << field.log_[0];
137 for (int i = 1; i < 256; i++) {
138 out << "," << field.log_[i];