Skip to content

Commit df51933

Browse files
feat: translate HEX to Unicode String and ByteArray String
Signed-off-by: Andreas Reichel <andreas@manticore-projects.com>
1 parent c2ff4ae commit df51933

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/main/java/net/sf/jsqlparser/expression/HexValue.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111

1212
import net.sf.jsqlparser.parser.ASTNodeAccessImpl;
1313

14+
import java.nio.charset.StandardCharsets;
15+
1416
public class HexValue extends ASTNodeAccessImpl implements Expression {
1517

1618
private String value;
@@ -61,4 +63,31 @@ public Long getLong() {
6163
public LongValue getLongValue() {
6264
return new LongValue(getLong());
6365
}
66+
67+
public static byte[] hexStringToByteArray(String s) {
68+
int len = s.length();
69+
byte[] data = new byte[len / 2];
70+
for (int i = 0; i < len; i += 2) {
71+
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
72+
+ Character.digit(s.charAt(i + 1), 16));
73+
}
74+
return data;
75+
}
76+
77+
// `X'C3BC'` --> `'ü'`
78+
public StringValue getStringValue() {
79+
return new StringValue(
80+
new String(hexStringToByteArray(getDigits()), StandardCharsets.UTF_8));
81+
}
82+
83+
// `X'C3BC'` --> `\xC3\xBC`
84+
public StringValue getBlob() {
85+
StringBuilder builder = new StringBuilder();
86+
String digits = getDigits();
87+
int len = digits.length();
88+
for (int i = 0; i < len; i += 2) {
89+
builder.append("\\x").append(digits.charAt(i)).append(digits.charAt(i + 1));
90+
}
91+
return new StringValue(builder.toString());
92+
}
6493
}

src/test/java/net/sf/jsqlparser/expression/HexValueTest.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class HexValueTest {
1919

2020
@Test
2121
void testHexCode() throws JSQLParserException {
22-
String sqlString = "SELECT 0xF001, X'00A1'";
22+
String sqlString = "SELECT 0xF001, X'00A1', X'C3BC'";
2323
PlainSelect select = (PlainSelect) CCJSqlParserUtil.parse(sqlString);
2424

2525
HexValue hex1 = (HexValue) select.getSelectItem(0).getExpression();
@@ -31,5 +31,12 @@ void testHexCode() throws JSQLParserException {
3131
Assertions.assertEquals("00A1", hex2.getDigits());
3232
Assertions.assertEquals(161, hex2.getLong());
3333
Assertions.assertEquals(161, hex2.getLongValue().getValue());
34+
35+
HexValue hex3 = (HexValue) select.getSelectItem(2).getExpression();
36+
Assertions.assertEquals("C3BC", hex3.getDigits());
37+
Assertions.assertEquals("'ü'", hex3.getStringValue().toString());
38+
Assertions.assertEquals("ü", hex3.getStringValue().getValue());
39+
40+
Assertions.assertEquals("'\\xC3\\xBC'", hex3.getBlob().toString());
3441
}
3542
}

0 commit comments

Comments
 (0)