C级上的显式类型转换

时间:2017-08-11 08:04:58

标签: c type-conversion bitwise-operators bit-shift

如果我的c代码是:

fig= plt.figure(figsize=(8,4))
plot_ax = fig.add_subplot(121)
bar_ax = fig.add_subplot(122, projection = 'polar')

plot_ax.imshow(
    np.dstack((d_norm,m_norm, np.zeros_like(directions))),
    aspect = 'auto',
    extent = (0,100,0,100),
)

theta, R = np.meshgrid(
    np.linspace(0,2*np.pi,100),
    np.linspace(0,1,100),
)

t,r = np.meshgrid(
    np.linspace(0,1,99),
    np.linspace(0,1,100),
)    

image = np.dstack((t, r, np.zeros_like(r)))

color = image.reshape((image.shape[0]*image.shape[1],image.shape[2]))

bar_ax.pcolormesh(
    theta,R,
    np.zeros_like(R),
    color = color,
)

bar_ax.set_xticks(np.linspace(0,2*np.pi,5)[:-1])
bar_ax.set_xticklabels(
    ['{:.2}'.format(i) for i in np.linspace(np.min(directions),np.max(directions),5)[:-1]]
)
bar_ax.set_yticks(np.linspace(0,1,5))
bar_ax.set_yticklabels(
    ['{:.2}'.format(i) for i in np.linspace(np.min(magnitude),np.max(magnitude),5)]
)
bar_ax.grid('off')

plt.show()

Buffer的每个索引都有什么?我不确定类型转换是如何在逐位的水平上工作的。它是否将unsigned char Buffer[4] = { 0, 0, 0, 0}; unsigned long Odometer = 0xff00ff00; Buffer[3] = Odometer & 0xff; Odometer = Odometer >> 8; Buffer[2] = (unsigned char)(Odometer & 0xff); Odometer = Odometer >> 8; Buffer[1] = (unsigned char)(Odometer & 0xff); Odometer = Odometer >> 8; Buffer[0] = (unsigned char)(Odometer & 0xff); 中最重要的字节或最低有效字节传输到每个Odometer索引中?

1 个答案:

答案 0 :(得分:5)

存储Buffer[3]

Buffer[3] = Odometer & 0xff;

最后8位0xff00ff 00 和0xff

之间的掩码

然后你将Odometer 8位向右移动,这样你得到0x00ff00ff

存储Buffer[2]

Buffer[2] = Odometer & 0xff;

掩码在最后8位0x00ff00 ff 和0xff

之间

并掩饰

0xff & 0x00 == 0x00

<强>而

0xff & 0xff == 0xff

所以结果

Buffer[3] = 0x00;
Buffer[2] = 0xff;
Buffer[1] = 0x00;
Buffer[0] = 0xff;

<强>按位

0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1

所以0x00&amp; 0xff看起来像那样

|0|0|0|0|0|0|0|0|
|1|1|1|1|1|1|1|1|
-----------------
|0|0|0|0|0|0|0|0| <-- res

而0xff&amp; 0xff看起来像那样

|1|1|1|1|1|1|1|1|
|1|1|1|1|1|1|1|1|
-----------------
|1|1|1|1|1|1|1|1| <-- res