ctypes 数据类型转换
‘’’
字符串前加 b 表示这是一个 bytes 对象
作用:
b" "前缀表示:后面字符串是bytes 类型。
用处:
网络编程中,服务器和浏览器只认bytes 类型数据。
如:send 函数的参数和 recv 函数的返回值都是 bytes 类型
附:
在 Python3 中,bytes 和 str 的互相转换方式是
str.encode(‘utf-8’)
bytes.decode(‘utf-8’)
‘’’
bytes to string
print(“abcde.decode=”,b"abcde".decode(“utf-8”)) # --> ‘abcde’
print(“type(abcde.decode)=”,type(b"abcde".decode(“utf-8”))) # --> <class ‘str’>
string to bytes
print(“abcde.encode=”,“abcde”.encode(“utf-8”)) # --> b’abcde’
print(“type(abcde.encode)=”,type(“abcde”.encode(“utf-8”))) # --> <class ‘bytes’>
‘’’
python2.x range() 函数可创建一个整数列表,一般用在 for 循环中。
Python3 range() 返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时
候不会打印列表
‘’’
(一) python 原生数组 list
a = [0]*10
for i in range(0, len(a)):
print(a[i], end=’ ')
print(’\n’,end=’’)
(二) 生成 10 元素的 c_int 类型的数组
from ctypes import *
a = (c_int*10)()
for i in range(0,len(a)):
print(a[i],end=’ ')
‘’’
例1,对整数数组倒序的程序
定义 具有10个 c_int 元素的数组
编写一维数组的 倒序的程序
‘’’
N = 10
def outPut(A):
for i in range(0,N):
print(A[i],end=’’)
print(’\n’)
def arrReverse(A,N):
i = 0; j=N-1
while i<j:
A[i],A[j] = A[j],a[i]
i = i+1
j = j-1
a = (c_int*N)()
for i in range(0,N):
a[i]=i
print(“原数组:”)
outPut(a)
arrReverse(a,len(a))
print(“倒序数组:”)
outPut(a)
创建可变的 string buffer
Python 默认的 string 是不可变的,所以不能传递 string 到一个 C 函数去改变它的内容,# 所以需要使用 create_string_buffer,对应 Unicode 字符串,要使用 create_unicode_buffer,
参考链接:https://www.cnblogs.com/gaowengang/p/7919219.html
create_unicode_buffer( python的字符串 )
char占一个字节,只能表示256个字符,类似与汉字这种字符char是无法表示的,wchar_t在
我的64位机器上占4字节,用于表示更多的字符。
char是8位,ANSI编码,wchar_t是16位或32位,根据C或C++库而定,是Unicode编码
a = create_unicode_buffer( “张三买了一头小毛驴,花了1024.05元钱。”)
a = create_string_buffer( b"hello")
print ( “原字符:”)
print ( a.value )
arrReverse( a , len( a ) -1 )
print (“倒序字符串:”)
print ( a.value )
参考链接:https://blog.csdn.net/u012308586/article/details/105477621/
“”"
python-string和bytes的关系
python中可以直接使用decode()将bytes格式化成string,decode()里面可以指定encoding即指定解码方式。
将string转成bytes可以使用encode()方式,encode()也可以指定编码方式。
为什么要转换?
首先,python里面不存在字节字符串的格式化操作,即bytes是没办法格式化的,所以在需要将字符串格式化的时候,要先转成string。(另外说一句,如果想要字节字符串,可以先使用标准的文本字符串,然后将其编码为字节字符串)
再有就是在解析网页的时候,会遇到获取到的网页(比如使用requests.content)是字节字符串
,需要先转换一下在进行解析,当然像beautifulsoup这种的会自动解析,不需要转换。
https://blog.csdn.net/qq_25730711/article/details/53817256
https://blog.csdn.net/sinat_41104353/article/details/79283619
“”"