encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];通过在这个表达式中添加“& 0xff”来防止“int”提升。
时间: 2024-03-31 08:33:56 浏览: 17
在Java中,当一个byte类型的值被转换为int类型时,最高的24个位都被填充为其符号位的值。这种转换称为“符号扩展”,这可能会导致一些问题。
在你提供的代码中,当将byte类型的值val2与k << 4进行按位或运算时,结果的数据类型被提升为int。如果val2的最高位为1,则符号扩展将在结果中填充1,这可能导致错误的结果。
因此,为了避免这种情况,建议在这个表达式中添加“& 0xff”。这将限制结果在0到255之间,并避免符号扩展引起的问题。修改后的代码应该如下所示:
```
encodedData[encodedIndex++] = lookUpBase64Alphabet[(val2 | (k << 4)) & 0xff];
```
这可以确保结果的正确性,并避免任何潜在的问题。
相关问题
public static String encode(byte[] binaryData) { if (binaryData == null) { return null; } int lengthDataBits = binaryData.length * EIGHTBIT; if (lengthDataBits == 0) { return ""; } int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; char[] encodedData = null; encodedData = new char[numberQuartet * 4]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; for (int i = 0; i < numberTriplets; i++) { b1 = binaryData[dataIndex++]; b2 = binaryData[dataIndex++]; b3 = binaryData[dataIndex++]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; } // form integral number of 6-bit groups if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex++] = PAD; encodedData[encodedIndex++] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex++] = PAD; } return new String(encodedData); }重构该方法,将其认知复杂度从18降低到允许的15。
该方法是一个将二进制数据转换为Base64编码的方法。为了将其认知复杂度从18降低到允许的15,可以考虑以下几个方面:
1. 提取公共方法:将一些重复的代码提取出来,封装成一个公共的方法,使得原方法中的代码量减少。
2. 优化变量名:将一些变量名改得更加易懂,减少代码的理解难度。
3. 简化表达式:将一些复杂的表达式简化,使得代码更加易读。
4. 减少条件分支:尽量减少条件分支的使用,可以使用位运算等技巧来实现。
下面是重构后的代码:
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * 8;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % 24;
int numberTriplets = lengthDataBits / 24;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char[] encodedData = new char[numberQuartet * 4];
byte val1, val2, val3, k, l, b1, b2, b3;
int dataIndex = 0, encodedIndex = 0;
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
val1 = (byte) ((b1 >>> 2) & 0x3f);
val2 = (byte) (((b1 << 4) & 0x30) | ((b2 >>> 4) & 0x0f));
val3 = (byte) (((b2 << 2) & 0x3c) | ((b3 >>> 6) & 0x03));
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
if (fewerThan24bits == 8) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
val1 = (byte) ((b1 >>> 2) & 0x3f);
val2 = (byte) (k << 4);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2];
encodedData[encodedIndex++] = '=';
encodedData[encodedIndex++] = '=';
} else if (fewerThan24bits == 16) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
val1 = (byte) ((b1 >>> 2) & 0x3f);
val2 = (byte) (((b1 << 4) & 0x30) | ((b2 >>> 4) & 0x0f));
val3 = (byte) (l << 2);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val3];
encodedData[encodedIndex++] = '=';
}
return new String(encodedData);
}
待编译语言的基本语言成分:赋值语句、条件语句、while语句、表达式。 下面用BNF给出该语言的文法。<程序>->“problem”<标识符>“:”程序体“.”<程序体>->“begin”<语句串>“end” <语句串>-><语句>{;<语句>!} <语句>-><赋值语>|<条件语句>|<循环语句> <赋值语句>-><变量>“=”<表达式> <条件语句>->“if”<表达式>“then”<语句>“else”<语句> <循环语句>->“while”<表达式>“do”<语句> <表达式>-><项>{“+”><项>|“-”项>} <项>-><因子>{“*”<因子>|“/”<因子>} <因子>-><无符号常量>|<变量>|“(”表达式>“)” <变量>-><标识符> <标识符>::=字母{字母、数字} <无符号整数>::=数字{数字} 根据上述语法规则构造递归下降分析程序
好的,我可以帮你构造递归下降分析程序。根据上述BNF文法,我们可以将其转换为如下的语法规则:
```
<程序> -> "problem" <标识符> ":" <程序体> "."
<程序体> -> "begin" <语句串> "end"
<语句串> -> <语句> { ";" <语句> }
<语句> -> <赋值语句> | <条件语句> | <循环语句>
<赋值语句> -> <变量> "=" <表达式>
<条件语句> -> "if" <表达式> "then" <语句> "else" <语句>
<循环语句> -> "while" <表达式> "do" <语句>
<表达式> -> <项> { ("+" | "-") <项> }
<项> -> <因子> { ("*" | "/") <因子> }
<因子> -> <无符号常量> | <变量> | "(" <表达式> ")"
<变量> -> <标识符>
<标识符> -> 字母 { 字母 | 数字 }
<无符号常量> -> 数字 { 数字 }
```
接下来,我们按照递归下降分析的方法,分别对每个非终结符编写一个函数。具体实现如下:
```python
# 定义全局变量
pos = 0 # 记录当前处理到的位置
text = "" # 记录要分析的文本
def match(expected):
"""匹配终结符"""
global pos
if pos < len(text) and text[pos] == expected:
pos += 1
else:
raise Exception("Syntax Error: expected {} but got {}".format(expected, text[pos]))
def is_alpha(ch):
"""判断是否为字母"""
return ch.isalpha()
def is_digit(ch):
"""判断是否为数字"""
return ch.isdigit()
def program():
"""处理 <程序>"""
match("problem")
identifier()
match(":")
program_body()
match(".")
def program_body():
"""处理 <程序体>"""
match("begin")
statement_list()
match("end")
def statement_list():
"""处理 <语句串>"""
statement()
while pos < len(text) and text[pos] == ";":
match(";")
statement()
def statement():
"""处理 <语句>"""
if text[pos] == "if":
conditional_statement()
elif text[pos] == "while":
loop_statement()
else:
assignment_statement()
def assignment_statement():
"""处理 <赋值语句>"""
variable()
match("=")
expression()
def conditional_statement():
"""处理 <条件语句>"""
match("if")
expression()
match("then")
statement()
match("else")
statement()
def loop_statement():
"""处理 <循环语句>"""
match("while")
expression()
match("do")
statement()
def expression():
"""处理 <表达式>"""
term()
while pos < len(text) and text[pos] in ("+", "-"):
if text[pos] == "+":
match("+")
else:
match("-")
term()
def term():
"""处理 <项>"""
factor()
while pos < len(text) and text[pos] in ("*", "/"):
if text[pos] == "*":
match("*")
else:
match("/")
factor()
def factor():
"""处理 <因子>"""
if is_digit(text[pos]):
unsigned_constant()
elif text[pos] == "(":
match("(")
expression()
match(")")
else:
variable()
def variable():
"""处理 <变量>"""
identifier()
def identifier():
"""处理 <标识符>"""
if not is_alpha(text[pos]):
raise Exception("Syntax Error: expected an alphabet but got {}".format(text[pos]))
pos += 1
while pos < len(text) and (is_alpha(text[pos]) or is_digit(text[pos])):
pos += 1
def unsigned_constant():
"""处理 <无符号常量>"""
if not is_digit(text[pos]):
raise Exception("Syntax Error: expected a digit but got {}".format(text[pos]))
pos += 1
while pos < len(text) and is_digit(text[pos]):
pos += 1
def parse(input_text):
"""解析输入文本"""
global pos, text
pos = 0
text = input_text
program()
if pos == len(text):
print("Parsing Succeeded")
else:
raise Exception("Syntax Error: unexpected end of input")
```
在上述代码中,我们定义了全局变量 `pos` 和 `text`,分别表示当前处理到的位置和要分析的文本。然后,我们编写了每个非终结符对应的函数,如 `program()`、`program_body()`、`statement_list()` 等。
在每个函数中,我们使用了递归的方法,不断调用其他函数,处理重复出现的子表达式。
最后,我们编写了一个 `parse()` 函数,用来解析输入文本。在解析过程中,我们首先调用 `program()` 函数,然后检查是否已经处理完了整个输入文本。
使用时,只需要调用 `parse()` 函数,传入要分析的文本即可。例如,对于输入文本:
```
problem example:
begin
x = 2 * (3 + y) / 4;
if x > 0 then
y = 2;
else
y = 3;
while y < 10 do
y = y + 1;
end
end.
```
我们可以这样调用:
```python
parse("""problem example:
begin
x = 2 * (3 + y) / 4;
if x > 0 then
y = 2;
else
y = 3;
while y < 10 do
y = y + 1;
end
end.""")
```
程序将会输出 `"Parsing Succeeded"`,表示分析成功。如果输入的文本不符合语法规则,则会抛出异常,给出相应的错误信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)