Skip to content

Commit

Permalink
Python/Construct: Use unsigned char representation when converting …
Browse files Browse the repository at this point in the history
…to bytes using `.as<bytes>`

That means that converted array expected to be an array of integers in the range [0, 255].

Perl and Ruby also uses unsigned representation ('C*')
  • Loading branch information
Mingun committed Mar 18, 2024
1 parent 6aef6fa commit 8cf77c4
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 8cf77c4

Please sign in to comment.