使用PN532模块时出现bytearrays相关TypeError问题求助
Hey there! Let's break down and fix that TypeError you're hitting when working with your PN532 module.
The Root Cause
That error message spells out exactly what's wrong: when you try to assign to data[2:8], the value you're using doesn't match the type requirements for bytes slice assignment in Python 3. Bytes objects only accept three types of values here:
- A
bytesobject - A buffer-compatible object
- An iterable where every element is an integer between 0 and 255
Your line data[2:8] = value is failing because value is none of these—chances are it's a regular string, a single integer, or another incompatible type.
Step-by-Step Fixes
Let's cover the most common scenarios for what value might be:
1. If value is a string
You need to convert the string to a bytes object, and make sure it fits exactly into the 6-byte slice (since data[2:8] covers 6 positions). Use encode() to convert, then adjust the length as needed:
# Example: value is a string like "MYNFC12" value = "MYNFC12" # Convert to bytes, truncate to 6 chars if too long, pad with null bytes if too short value_bytes = value.encode('utf-8')[:6].ljust(6, b'\x00') data[2:8] = value_bytes
2. If value is a numeric integer
You'll need to pack the integer into a 6-byte sequence using Python's struct module—this is common for numeric NFC tag data. For big-endian formatting (standard in most NFC operations):
import struct # Example: value is an integer like 987654321 value = 987654321 # Pack as an 8-byte unsigned long long, then slice to get the last 6 bytes # Adjust the format string if you need a different byte order or size value_bytes = struct.pack('>Q', value)[2:] data[2:8] = value_bytes
3. If value is a list of integers (with invalid values)
Double-check that every integer in the list falls between 0 and 255—NFC tags use 8-bit bytes, so values outside this range are invalid. Clamp and adjust the list length to 6 elements:
# Example: value has out-of-range integers value = [300, 15, 210, 500] # Clamp values to 0-255 valid_value = [max(0, min(x, 255)) for x in value] # Pad with 0s to make sure we have exactly 6 elements valid_value = valid_value[:6] + [0]*(6 - len(valid_value)) data[2:8] = valid_value
Quick Debug Tip
First, confirm what type value actually is by adding this line right before the erroring code:
print(f"Type of value: {type(value)}, Value: {value}")
This will tell you exactly what you're working with, making it way easier to apply the right fix.
内容的提问来源于stack exchange,提问作者undergrad2020

