什么是golang与PHP / Ruby的unpack(“ C *”,。)等价?

时间:2018-11-25 13:49:00

标签: go

PHP和ruby一直是golang的新手,它具有将二进制文件解压缩为数组的解压缩功能。我正在尝试找出如何在golang中执行以下操作。

$test = "\01\00\02\03";
print_r(unpack("C*", $test)); // [1,0,2,3]

s = "\01\00\02\03"
arr = s.unpack("C*")
p(arr) # [1,0,2,3]

使用golang进行此操作的最佳方法是什么?

1 个答案:

答案 0 :(得分:6)

请首先注意,您的PHP字符串let fragmentShader = ` uniform vec2 u_resolution; uniform float u_time; const int octaves = 6; const float seed = 43758.5453123; const float seed2 = 73156.8473192; vec2 random2(vec2 st, float seed){ st = vec2( dot(st,vec2(127.1,311.7)), dot(st,vec2(269.5,183.3)) ); return -1.0 + 2.0*fract(sin(st)*seed); } float noise(vec2 st, float seed) { vec2 i = floor(st); vec2 f = fract(st); vec2 u = f*f*(3.0-2.0*f); return mix( mix( dot( random2(i + vec2(0.0,0.0), seed ), f - vec2(0.0,0.0) ), dot( random2(i + vec2(1.0,0.0), seed ), f - vec2(1.0,0.0) ), u.x), mix( dot( random2(i + vec2(0.0,1.0), seed ), f - vec2(0.0,1.0) ), dot( random2(i + vec2(1.0,1.0), seed ), f - vec2(1.0,1.0) ), u.x), u.y); } float fbm1(in vec2 _st, float seed) { float v = 0.0; float a = 0.5; vec2 shift = vec2(100.0); mat2 rot = mat2(cos(0.5), sin(0.5), -sin(0.5), cos(0.50)); for (int i = 0; i < octaves; ++i) { v += a * noise(_st, seed); _st = rot * _st * 2.0 + shift; a *= 0.4; } return v; } float pattern(vec2 uv, float seed, float time, inout vec2 q, inout vec2 r) { q = vec2( fbm1( uv + vec2(0.0,0.0), seed ), fbm1( uv + vec2(5.2,1.3), seed ) ); r = vec2( fbm1( uv + 4.0*q + vec2(1.7 - time / 2.,9.2), seed ), fbm1( uv + 4.0*q + vec2(8.3 - time / 2.,2.8), seed ) ); vec2 s = vec2( fbm1( uv + 4.0*r + vec2(21.7 - time / 2.,90.2), seed ), fbm1( uv + 4.0*r + vec2(80.3 - time / 2.,20.8), seed ) ); vec2 t = vec2( fbm1( uv + 4.0*s + vec2(121.7 - time / 2.,90.2), seed ), fbm1( uv + 4.0*s + vec2(180.3 - time / 2.,20.8), seed ) ); float rtn = fbm1( uv + 4.0*t, seed ); rtn = clamp(rtn, 0., .5); return rtn; } void main() { vec2 uv = (gl_FragCoord.xy - 0.5 * u_resolution.xy) / u_resolution.y; uv *= 1. + dot(uv, uv)*.3; float time = u_time / 20.; mat2 rot = mat2(cos(time), sin(time), -sin(time), cos(time)); uv = rot * uv; uv *= 1.4 + sin(time) * .3; uv.x -= time; vec2 q = vec2(0.,0.); vec2 r = vec2(0.,0.); vec3 colour = vec3(pattern(uv, seed, time, q, r)); float QR = clamp(dot(q, r), -1., 1.); colour += vec3((q.x + q.y) + QR * 30., QR * 15., r.x * r.y + QR * 5. ); colour += .1; colour = clamp(colour, 0.05, 1.); gl_FragColor = vec4(colour + (abs(colour) * .1), 1.); } ` 是由"\01\00\02\03"\x01\x00\x02这四个字节组成的字符串, {1}}被解释为八进制。有关详细信息,请参见the documentation for double quoted strings

在Go中,语法\x03不正确。与C中一样,八进制序列必须具有3个数字,即"\01"。因此,PHP字符串\01在Go \001中(在PHP中也可以使用)。考虑到这一点,解包很容易,并且不需要像"\01\00\02\03"这样的特殊功能:

"\001\000\002\003"

输出:

unpack