Skip to content

Commit

Permalink
Merge pull request #282 from Mingun/fix-python-as-bytes
Browse files Browse the repository at this point in the history
Python/Construct: Use `unsigned char` representation when converting to `bytes`
  • Loading branch information
generalmimon authored Mar 21, 2024
2 parents b7d5169 + 8cf77c4 commit 6cab5ab
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@ class TranslatorSpec extends AnyFunSpec {
LuaCompiler -> "???",
PerlCompiler -> "pack('C*', ((0 + 1), 5))",
PHPCompiler -> "pack('C*', (0 + 1), 5)",
PythonCompiler -> "struct.pack('2b', (0 + 1), 5)",
PythonCompiler -> "struct.pack('2B', (0 + 1), 5)",
RubyCompiler -> "[(0 + 1), 5].pack('C*')"
))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ class PythonTranslator(provider: TypeProvider, importList: ImportList) extends B
"b\"" + Utils.hexEscapeByteArray(arr) + "\""
override def doByteArrayNonLiteral(elts: Seq[Ast.expr]): String = {
importList.add("import struct")
s"struct.pack('${elts.length}b', ${elts.map(translate).mkString(", ")})"
// Use `unsigned char` representation (see https://docs.python.org/3/library/struct.html#struct-format-strings)
s"struct.pack('${elts.length}B', ${elts.map(translate).mkString(", ")})"
}

override def doLocalName(s: String) = {
Expand Down

0 comments on commit 6cab5ab

Please sign in to comment.