-
Notifications
You must be signed in to change notification settings - Fork 7
cn_pointer_like
HouQiming edited this page Nov 17, 2017
·
1 revision
在JC里如果需要直接操作底层的二进制表达的话,可以用数组的slice功能结合ConvertToAsBinary
方法来实现。以下是一个例子程序:
import "system.jc"
import System.Console.*
(function(){
byte_array = [
u8(0), u8(1), u8(2), u8(3),
u8(4), u8(5), u8(6), u8(7),
u8(8), u8(9), u8(10), u8(11)]
int_array = byte_array[4:7].ConvertToAsBinary(int)
Writeln('byte_array is ',byte_array)
Writeln('int_array is ',int_array,' which is [0x',
formatNumber(int_array[0], {base:16,align:8}), '] in hex')
Writeln('set int_array[0] to 0x07070707')
int_array[0]=0x07070707
Writeln('byte_array is now ',byte_array)
})()
输出是:
byte_array is [0,1,2,3,4,5,6,7,8,9,10,11]
int_array is [117835012] which is [0x07060504] in hex
set int_array[0] to 0x07070707
byte_array is now [0,1,2,3,7,7,7,7,8,9,10,11]
在上面程序中,int_array = byte_array[4:7].ConvertToAsBinary(int)
。把int_array
绑定到了byte_array
的第4到第7个元素,也就是原本值为4、5、6、7的4个元素。两个array共享这段地址空间,改一个另一个就会跟着变。写成C的话,大致相当于:
unsigned char byte_array[12] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int* int_array = (int*)(byte_array+4);
这样的感觉。
在JC中如果需要类似memcpy
的功能的话,建议尽量用内置的copy
函数,也就是数组拷贝来代替,比如这样:
import "system.jc"
import System.Console.*
(function(){
byte_array = [
u8(0), u8(1), u8(2), u8(3),
u8(4), u8(5), u8(6), u8(7),
u8(8), u8(9), u8(10), u8(11)]
Writeln('byte_array is ',byte_array)
Writeln('copy byte_array[0:3] from byte_array[4:7]')
copy(byte_array[0:3], byte_array[4:7])
Writeln('byte_array is now ',byte_array)
})()
输出:
byte_array is [0,1,2,3,4,5,6,7,8,9,10,11]
copy byte_array[0:3] from byte_array[4:7]
byte_array is now [4,5,6,7,4,5,6,7,8,9,10,11]