how to calculate the byte sum of struct in swift - swift

this is the code in OC
It is not easy for me to convert it to swift, especially the calculate of check sum part
If anyone knows how to write, please let me know. Thank you.
OC Code:
MessageToOnboard {
unsigned char header[2];
ushort length;
uint8_t msgID;
uint missionID;
ushort wayPointID;
double lon;
double lat;
float height;
unsigned char wayPointAction;
// unsigned long reserve;
unsigned char checkSum;
}
MessageToOnboard message;
message.header[0] = 'Q';
message.header[1] = 'Z';
message.msgID = 0x21;
message.missionID = 12;
message.wayPointID = 10;
message.lon = 34.2323242;
message.lat = 68.2121221;
message.height = 30;
message.wayPointAction = '2';
message.length = sizeof(message) -5;
uint8_t *msgBIn = (uint8_t *)&message;
int iLength = sizeof(message);
uint8_t icheckSum = 0;
for (int i = 0 ; i < iLength - 3; i++)
{
icheckSum += *(msgBIn+2+i);
}
message.checkSum = icheckSum;
NSData *data = [[NSData alloc] initWithBytes:&message length:sizeof(message)];
Swift Code:
I tried this, but it is not right, I don't know how to use pointer to calculate the sum bytes of struct in swift
let msgBIn = withUnsafePointer(to: &message) {$0}
print(msgBIn.pointee)
let iLength: Int = MemoryLayout<MessageToOnboard>.size
let icheckSum: UInt8 = 0
for i in 0..<iLength - 1 {
let pointer = msgBIn.advanced(by: 2 + i)
icheckSum += UInt8(pointer)
}

finally, solved this problem
Message is a Struct
func sumByte(msg: inout Message) -> UInt8 {
let pointer = withUnsafePointer(to: msg) {UnsafeRawPointer($0)}
var sum: UInt8 = 0;
for i in 0..<(MemoryLayout<Message>.size) {
let nextP = pointer.advanced(by: i)
sum += nextP.load(as: UInt8.self)
}
return sum;
}

Related

Swift Sprite Nodes Colliding

I want to enable two SKSpriteNodes to pass through one another. From my understanding the following code should do the trick:
beam?.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: beam!.size.width - 40, height: beam!.size.height/4));
beam?.physicsBody?.categoryBitMask = ColliderType.BEAM;
beam?.physicsBody?.contactTestBitMask = ColliderType.ENEMY;
beam?.physicsBody?.collisionBitMask = 0;
beam?.physicsBody?.affectedByGravity = false;
beam?.physicsBody?.allowsRotation = false;
item?.physicsBody?.categoryBitMask = ColliderType.CRATES;
item?.physicsBody?.contactTestBitMask = ColliderType.PLAYER;
item?.physicsBody?.collisionBitMask = ColliderType.GROUND;
item?.physicsBody?.affectedByGravity = true;
item?.physicsBody?.allowsRotation = false;
As neither should be picked up by the by the other's collider type. I have tried many different methods already including setting their collision bit masks to 0.
When the two nodes collide the item moves below the beam. Then when the beam disappears the item moves back into its original place. The item must remain dynamic to other nodes, but advice on this topic is greatly appreciated. Thanks.
struct ColliderType {
static let PLAYER: UInt32 = 0;
static let GROUND: UInt32 = 1;
static let CRATES: UInt32 = 2;
static let BULLET: UInt32 = 3;
static let ENEMY: UInt32 = 4;
static let EXPLOSION: UInt32 = 5;
static let UFO: UInt32 = 6;
static let UFOBOMB: UInt32 = 7;
static let SHIELD: UInt32 = 8;
static let BEAM: UInt32 = 9;
}

Swift: How to make sure that code is not optimized out?

I want to zero-out the contents of an UnsafeMutablePointer in Swift.
In C you usually have something like this:
void freeSecure(void *buffer, uint64_t size) {
// Create volatile pointer to make sure that the code won't be optimized away
volatile uint8_t *ptr = buffer;
for (uint64_t i = 0; i < size; i++) ptr[i] = 0x00;
free(buffer);
}
How can I achieve the same thing in Swift?
// Is extension of `UnsafeMutablePointer`
public func KC_dealloc(allocated: Int) {
if num == 0 {
self.destroy()
self.dealloc(allocated)
return
}
let byteCount = sizeof(Memory) * allocated
let ptr = UnsafeMutablePointer<UInt8>(self) // volatile???
for var i = 0; i < byteCount; i++ {
ptr[i] = 0x00
}
self.destroy()
self.dealloc(allocated)
}
Okay, I asked the same question in the Apple-developer-forum and some guy there pointed me to the memset_s-function which does what I want.
So my Swift-code should look like this:
// Is extension of `UnsafeMutablePointer`
public func KC_dealloc(allocated: Int) {
if num == 0 {
self.destroy()
self.dealloc(allocated)
return
}
let byteCount = sizeof(Memory) * allocated
let ptr = UnsafeMutablePointer<UInt8>(self) // volatile???
memset_s(ptr, byteCount, 0x00, byteCount) // Defined in C11
self.destroy()
self.dealloc(allocated)
}

Getting value from unSafeMutablePointer Int16 in Swift for audio data purposes

I'm working to convert to Swift this code which helps get me get audio data for visualizations. The code I'm working with in Obj C, which works well, is:
while (reader.status == AVAssetReaderStatusReading) {
AVAssetReaderTrackOutput *trackOutput = (AVAssetReaderTrackOutput *)[reader.outputs objectAtIndex:0];
self.sampleBufferRef = [trackOutput copyNextSampleBuffer];
if (self.sampleBufferRef) {
CMBlockBufferRef blockBufferRef = CMSampleBufferGetDataBuffer(self.sampleBufferRef);
size_t bufferLength = CMBlockBufferGetDataLength(blockBufferRef);
void *data = malloc(bufferLength);
CMBlockBufferCopyDataBytes(blockBufferRef, 0, bufferLength, data);
SInt16 *samples = (SInt16 *)data;
int sampleCount = bufferLength / bytesPerInputSample;
for (int i=0; i<sampleCount; i+=100) {
Float32 sample = (Float32) *samples++;
sample = decibel(sample);
sample = minMaxX(sample,noiseFloor,0);
tally += sample;
for (int j=1; j<channelCount; j++)
samples++;
tallyCount++;
if (tallyCount == downsampleFactor) {
sample = tally / tallyCount;
maximum = maximum > sample ? maximum : sample;
[fullSongData appendBytes:&sample length:sizeof(sample)];//tried dividing the sample by 2
tally = 0;
tallyCount = 0;
outSamples++;
}
}
CMSampleBufferInvalidate(self.sampleBufferRef);
CFRelease(self.sampleBufferRef);
free(data);
}
}
In Swift, I'm trying to write is this part:
while (reader.status == AVAssetReaderStatus.Reading) {
var trackOutput = reader.outputs[0] as! AVAssetReaderTrackOutput
self.sampleBufferRef = trackOutput.copyNextSampleBuffer()
if (self.sampleBufferRef != nil) {
let blockBufferRef = CMSampleBufferGetDataBuffer(self.sampleBufferRef)
let bufferLength = CMBlockBufferGetDataLength(blockBufferRef)
var data = NSMutableData(length: bufferLength)
CMBlockBufferCopyDataBytes(blockBufferRef, 0, bufferLength, data!.mutableBytes)
var samples = UnsafeMutablePointer<Int16>(data!.mutableBytes)
var sampleCount = Int32(bufferLength)/bytesPerInputSample
for var i = 0; i < Int(sampleCount); i++ {
var sampleValue = CGFloat(samples[i]) etc. etc.
However, when I println() sampleValue is just comes out (Opaque Value) in the console. I can't figure out how to actually read the sampleValue.
I'm new at trying to read audio data for visualization purposes. Any help on getting a buffer of audio data to work with would be helpful. Thank you.
Use stride?
let bytesPerInputSample = 4 // assumption ;)
var samplePtr = data.mutableBytes
for _ in stride(from: 0, to: data.length, by: bytesPerInputSample) {
let currentSample = Data(bytes: samplePtr, count: bytesPerInputSample)
// do whatever is needed with current sample
//...
// increase ptr by size of sample
samplePtr = samplePtr + bytesPerInputSample
}

cocos2d content.size, boundingBox and size

im writing a game to find the differences between 2 images. i created a subclass of CCSprite, Spot. firstly i tried to create small images and add itself according to it's position, but later i found the position is hard to determine, since it's hard to avoid offset of 1 or 2 pixels.
then i tried to make the Spot the same size as the image, with the other part transparent. but I still need to find out the 'hotspot' of finger tap. but when i use CGRectContainsPoint([self boundingBox], touchLocation), it's actually the whole image.
so is there any other way to do this? like content.size or self.size, and make a CGRect out of it's non-transparent part?
Thank you.
I figured it out now. here is my code: (it's actually quite simple
-(void) findRect:(NSString*) fn {
//the origin of mTex is top left
//the origin of CGRect is top left, in the coordinate system inside the image
int topLeftX = 0;
int topLeftY = 0;
for (int i = 0; i < image_width; i += 10) {
for (int j = 0; j < image_height; j += 10) {
if (([mTex pixelAt:ccp(i, j)].a & 0xFF) != 0) {
topLeftX = i;
topLeftY = j;
goto outer;
}
}
}
outer:;
int topRightX = 0;
for (int i = topLeftX; i < image_width; i += 10) {
if (([mTex pixelAt:ccp(i, topLeftY)].a & 0xFF) == 0) {
topRightX = i;
break;
}
}
if (topRightX == 0) {
topRightX = image_width - 1;
}
int bottomLeftY = 0;
for (int i = topLeftY; i < image_height; i += 10) {
if (([mTex pixelAt:ccp(topLeftX, i)].a & 0xFF) == 0) {
bottomLeftY = i;
break;
}
}
if (bottomLeftY == 0) {
bottomLeftY = image_height - 1;
}
areaRect = CGRectMake(topLeftX, topLeftY, topRightX - topLeftX, bottomLeftY - topLeftY);
}

How to make a struct maker like CGRectMake (iphone)

i have a struct HLRange with two CGFloat's
struct HOLRange
{
CGFloat min;
CGFloat max;
};
typedef struct HOLRange HOLRange;
but how do i make a function like HLRangeMake(1,2); .. like CGRectMake?
--EDIT--
my header file
#import <Foundation/Foundation.h>
struct HOLRange
{
CGFloat min;
CGFloat max;
};
typedef struct HOLRange HOLRange;
HOLRange HOLRangeMake(CGFloat min, CGFloat max) {
HOLRange range;
range.min = min;
range.max = max;
return range;
}
#interface Structs : NSObject {
}
#end
error message: ld: duplicate symbol _HOLRangeMake in /Users/Documents/projects/iphone/test/catalog/base1/build/base1.build/Debug-iphoneos/base1.build/Objects-normal/armv6/base1AppDelegate.o and /Users/Documents/projects/iphone/test/catalog/base1/build/base1.build/Debug-iphoneos/base1.build/Objects-normal/armv6/main.o
HOLRange HLRangeMake(CGFloat min, CGFloat max) {
HOLRange range;
range.min = min;
range.max = max;
return range;
}
You can see CGRectMake source in CGGeometry.h so you can do the same:
CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x; rect.origin.y = y;
rect.size.width = width; rect.size.height = height;
return rect;
}
Edit: You must either define your function as inline or move its implementation to .m file. You're getting linker errors as you function becomes defined in every compile unit that imports HoleRange.h (?) header.
Old post. However, I'd like to share my method of resolving this problem for future viewers.
typdef struct _HOLRange {
CGFloat min;
CGFloat max;
} HOLRange;
static inline HOLRange(CGFloat min, CGFloat max) {
return (HOLRange) {min, max};
}
You can define your stuct and Make function like this. Short and quick.
I like the format of this better. It makes more sense visually and seems more "correct."
typedef struct {
CGFloat min;
CGFloat max;
} HOLRange;
static inline HOLRange HOLRangeMake(CGFloat min, CGFloat max) {
HOLRange range;
range.min = min;
range.max = max;
return range;
}