Skip to content

Commit

Permalink
feat: translate HEX to Unicode String and ByteArray String
Browse files Browse the repository at this point in the history
Signed-off-by: Andreas Reichel <andreas@manticore-projects.com>
  • Loading branch information
manticore-projects committed Apr 26, 2024
1 parent c2ff4ae commit df51933
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
29 changes: 29 additions & 0 deletions src/main/java/net/sf/jsqlparser/expression/HexValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

import net.sf.jsqlparser.parser.ASTNodeAccessImpl;

import java.nio.charset.StandardCharsets;

public class HexValue extends ASTNodeAccessImpl implements Expression {

private String value;
Expand Down Expand Up @@ -61,4 +63,31 @@ public Long getLong() {
public LongValue getLongValue() {
return new LongValue(getLong());
}

public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}

// `X'C3BC'` --> `'ü'`
public StringValue getStringValue() {
return new StringValue(
new String(hexStringToByteArray(getDigits()), StandardCharsets.UTF_8));
}

// `X'C3BC'` --> `\xC3\xBC`
public StringValue getBlob() {
StringBuilder builder = new StringBuilder();
String digits = getDigits();
int len = digits.length();
for (int i = 0; i < len; i += 2) {
builder.append("\\x").append(digits.charAt(i)).append(digits.charAt(i + 1));
}
return new StringValue(builder.toString());
}
}
9 changes: 8 additions & 1 deletion src/test/java/net/sf/jsqlparser/expression/HexValueTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class HexValueTest {

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

HexValue hex1 = (HexValue) select.getSelectItem(0).getExpression();
Expand All @@ -31,5 +31,12 @@ void testHexCode() throws JSQLParserException {
Assertions.assertEquals("00A1", hex2.getDigits());
Assertions.assertEquals(161, hex2.getLong());
Assertions.assertEquals(161, hex2.getLongValue().getValue());

HexValue hex3 = (HexValue) select.getSelectItem(2).getExpression();
Assertions.assertEquals("C3BC", hex3.getDigits());
Assertions.assertEquals("'ü'", hex3.getStringValue().toString());
Assertions.assertEquals("ü", hex3.getStringValue().getValue());

Assertions.assertEquals("'\\xC3\\xBC'", hex3.getBlob().toString());
}
}

0 comments on commit df51933

Please sign in to comment.